2

I have this code:

str = func(parameter)
if not str:
   do something.

the function func() return a string on success and '' on failure. The do something should happen only if str actualy contain a string.

Is it possible to do the assigmnt to str on the IF statment itself?

ban
  • 187
  • 1
  • 1
  • 10
  • you should define that inside the function `func`. – Siva Shanmugam Sep 28 '16 at 06:27
  • Possibly a duplicate of "[https://stackoverflow.com/q/8826521/90527](Python: avoiding if condition for this code?)" (though this question is more focused on the general problem, rather than on specific code, and is thus a better expression of the issue). – outis May 02 '22 at 01:30

5 Answers5

2

In one word: no. In Python assignment is a statement, not an expression.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
1

Why not try it yourself,

if not (a = some_func()):
  do something
      ^
SyntaxError: invalid syntax

So, no.

Net Myth
  • 441
  • 1
  • 5
  • 14
1

PEP 572 added syntax for assignment expressions. Specifically, using := (called the "walrus operator") for assignment is an expression, and thus can be used in if conditions.

if not (thing := findThing(name)):
    thing = createThing(name, *otherArgs)

Note that := is easy to abuse. If the condition is anything more complex than a direct test (i.e. if value := expresion:) or a not applied to the assignment result (such as in the 1st sample above), it's likely more readable to write the assignment on a separate line.

outis
  • 75,655
  • 22
  • 151
  • 221
0

With the below code snippet, if the func returns a string of length > 0 only then the do something part will happen

str = func(parameter)
if str:
   do something
0

You can try this, it's the shortest version I could come up with:

if func(parameter):
   do something.
user3543300
  • 499
  • 2
  • 9
  • 27