views:

122

answers:

5

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."
A: 

The same syntax works in Python.

Matti Virkkunen
+2  A: 

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
cypheon
+1  A: 

Short-circuits work in Python too.

return a or b
Ashish
+2  A: 

And if you need to be able to handle "false-ish" values more specifically (e.g., 0 or '' are good values but None and False are not), there's the more verbose "conditional expression" (a.k.a. ternary operator) introduced in Python 2.5:

return x if <cond> else y

where <cond> can be any condition:

return x if isinstance(x, basestring) else y
Will McCutchen
+1  A: 

Actually there is a difference in Python ehre: If a variable named some_var is not defined you can't access it to know it does not exist - you will get a NameError exception.

This is so by design: undefined variable names do not have an "undefined" or "null" value, they raise an Exception, and that is one of the greates differences from Python to most dynamic typed languages.

So, it is not Pythonic to get to a statement where some_var might or not be defined. In a good program it would have been defined, even if to contain "None" or "False" - In that case the "or" idiom would work, but the recommended way to handle it s to use the expression if like in:

return some_var if some_var else "some_var contains a False Value"

If you happen tohave code where some_var might not be defined, and cannot for soemr eason change that, you can check if the string "some_var" exists as a key in the dicitonary of localv ariables, returned by locals() to know wether it was defined or not:

return some_var if "some_var" in locals() else "some_var was not defined"

That is not the most pythonic way either - having to deal witha variable that my not be defined is exceptional in Python code. So the best pratice would be to try to use the vars contents inside a try cause, and catch the "NameError" exception if the var does not exist:

try:
  return some_var
except NameError:
  return "some_var not defined"
jsbueno