Python if x as y
I often find myself doing something stupid like
if some_function():
self.value = some_function()
which makes the function execute twice. It will be fixed with something like
value = some_function():
if value:
self.value = value
It would be great if Python allowed something like
if some_function() as value:
self.value = value
Saves some space and is quite legible. I would even say it sounds pythonic.
So, I know this is invalid syntax, but is there a similar construct that I am not aware of? Should I be offering it to the Python Software Foundation?
Python intentionally disallows this construct by forcing the condition to if
be an expression and making the assignments not an expression, under the motto "Explicit is better than implicit". You have to write
value = some_function():
if value:
self.value = value
(However, it works in Ruby, C, JavaScript, Java ... and any other language where assignment is an expression.)
You can always do:
>>> self.value = some_function() or self.value
def if_to_for(condition):
if condition: yield condition
for value in if_to_for(some_function()):
self.value = value
will work too.
If the condition is true, the loop will execute once, if it is false, it will not execute at all.
theoretically :
if (lambda v: globals().update({'value':v}) or v)(some_function()):
self.value = value
You are faster assigning the return of a function to a variable before you do if
. Also readability is calculated.