I found an interesting expression in Ruby:
a ||= "new"
This means that if a is not defined, a "new" value will be assigned to a; otherwise a will be the same as it. This is useful when executing some database query. If the value is set, I do not want to run another database query.
So, I tried similar thinking in Python:
a = a if a is not None else "new"
Failed. I think this is because you cannot do "a = a" in Python if a is not defined.
So, the solutions I can execute check locals () and globals () or use try ... except expression:
myVar = myVar if 'myVar' in locals() and 'myVar' in globals() else "new"
or
try:
myVar
except NameError:
myVar = None
myVar = myVar if myVar else "new"
As we can see, the solutions are not so elegant. So I would like to ask if there is a better way to do this?
source
share