Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way of choosing 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 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."
like image 413
Vlad the Impala Avatar asked Dec 19 '25 08:12

Vlad the Impala


1 Answers

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
like image 70
cypheon Avatar answered Dec 20 '25 20:12

cypheon