I came across an interesting expression in Ruby:
a ||= "new"
It means that if a is not defined, the “new” value will be assigned to a; otherwise, a will be the same as it is. It is useful when doing some DB query. If the value is set, I don’t want to fire another DB query.
So I tried the similar mindset in Python:
a = a if a is not None else "new"
It failed. I think that it because you cannot do “a = a” in Python, if a is not defined.
So the solutions that I can come out are checking locals() and globals(), or using 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 that elegant. So I’d like to ask, is there any better way of doing this?
How about?
It’s not very short but does clearly (at least to me) explain the intent of the code.