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 or operator in Python is guaranteed to return one of its operands, in case the left expression evaluates to False, 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 the get() 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:
>>> locals().get('some_var', "some_var doesn't exist.")
"some_var doesn't exist."
>>> some_var = 0
>>> locals().get('some_var', "some_var doesn't exist.")
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With