Dicts in Python have a very nice method get:
# m is some dict
m.get(k,v) # if m[k] exists, returns that, otherwise returns v
Is there some way to do this for any value? For example, in Perl I could do this:
return $some_var or "some_var doesn't exist."
The
oroperator in Python is guaranteed to return one of its operands, in case the left expression evaluates toFalse, the right one is evaluated and returned.Edit:
After re-reading your question, I noticed that I misunderstood it the first time. By using the
locals()built-in function, you can use theget()method for variables, just like you use it for dicts (although it’s neither very pretty nor pythonic), to check whether a value exists or not: