The cleanest way to choose between two values ​​in Python

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 any way to do this for any value? For example, in Perl, I could do this:

return $some_var or "some_var doesn't exist."
+3
source share
4 answers

An operator orin Python is guaranteed to return one of its operands if the left expression evaluates Falseto correct and evaluates and returns.

Edit

, . locals(), get() , dicts ( pythonic), , :

>>> 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
+2

"false-ish" (, 0 '' - , None False - ), " " (aka trernary operator), Python 2.5:

return x if <cond> else y

<cond> :

return x if isinstance(x, basestring) else y
+2

Python .

return a or b
+1

Python ehre : some_var , , , - NameError.

: undefined "undefined" "null", , Python .

, Pythonic, , some_var . , "None" "False" - "" , if, :

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

, some_var , , "some_var" dicitonary localv ariables, locals() , :

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

- , , Python. , vars try "NameError", var :

try:
  return some_var
except NameError:
  return "some_var not defined"
+1

Source: https://habr.com/ru/post/1756824/


All Articles