'Python - assign value and check condition in IF statment
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?
Solution 1:[1]
In one word: no. In Python assignment is a statement, not an expression.
Solution 2:[2]
Why not try it yourself,
if not (a = some_func()):
do something
^
SyntaxError: invalid syntax
So, no.
Solution 3:[3]
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
Solution 4:[4]
You can try this, it's the shortest version I could come up with:
if func(parameter):
do something.
Solution 5:[5]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bruno desthuilliers |
Solution 2 | Net Myth |
Solution 3 | Gopi Vinod Avvari |
Solution 4 | user3543300 |
Solution 5 |