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?
variable ||= value
is to set a default value to an already defined variable, using it to define variables that may or may not exist is IMHO poor practice. – CombatantmyVar = myVar if myVar else "new"
- be aware that this is python and not ruby, and a lot of things are considered to be False in a boolean context – Tourneything.foo = thing.foo or 'something else'
. Do you have an example of where you want to use it? – Communication