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?
source to share
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.)
source to share