3

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."
Vlad the Impala
  • 15,572
  • 16
  • 81
  • 124
  • My mistake, this wasn't working for my class for some reason. Voting to close, this seems obvious in retrospect. – Vlad the Impala Jul 27 '10 at 22:48
  • As the answers note, you can use the or operator like this in Python. But I'm curious: do people generally consider this idiom Pythonic? I haven't personally seen it in Python code, but I see it in Perl code all over the place. – Owen S. Jul 27 '10 at 22:48
  • 5
    That `return` statement doesn't do what you think it does. See http://stackoverflow.com/questions/1512547/what-is-the-difference-between-perls-or-and-and-short-circuit-op – mob Jul 27 '10 at 22:48
  • Your Perl code is wrong. The precedence of "or" is low. It will end up as the equivalent of `return($some_var) or "some_var doesn't exist"`. Thus you want: `return $some_var || "some_var doesn't exist"` or starting with Perl 5.10 using defined-or: `return $some_var // "some_var doesn't exist"`. Of course, you can always use parenthesis to make things clearer: `return($some_var // "some_var doesn't exist")` – tsee Jul 28 '10 at 10:30

4 Answers4

2

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,023
  • 1
  • 13
  • 22
2

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
  • 13,047
  • 3
  • 44
  • 43
1

Short-circuits work in Python too.

return a or b
Jungle Hunter
  • 7,233
  • 11
  • 42
  • 67
1

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
  • 99,910
  • 10
  • 151
  • 209