Reputation: 193
Is it possible to "re-use" the value of a parameter of an if
-clause?
I have a function that returns either True
or a dictionary:
def foo():
if random.randint(0, 1) == 0:
return True
else:
return {"time": time.time()}
If foo()
returns the dictionary, I also want to return it. If foo()
returns True
I want to just continue.
Currently I'm using:
if_value = foo()
if if_value is not True:
return if_value
My goal would be to avoid saving the return value of the function into a variable, because it makes my code really ugly (I need to do this about 20 times in a row).
When using a Python shell, it seems to work like this:
if function_that_returns_True_or_an_int() is not True:
return _
Any suggestions about this?
Upvotes: 0
Views: 159
Reputation: 117886
You can use the walrus operator (:=
) to declare a variable and assign to it, then do your comparison
if (x := your_function()) == condition:
# something
else:
# something else
print(x) # x is still a named variable and in scope
Upvotes: 1