Python Forum
How Right? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How Right? (/thread-14146.html)



How Right? - Cassie - Nov-16-2018

Hi everybody, I got a question

variable = dict_.get('var_name') or 'DEFAULT'
dict_ may has key, or not, his value is may empty or not. How I can decide this task? I don't wont reffer to dictionary twice.
Is using "or" in assign statement is bad practice?

How right do this in python, in more python way?

Thanks for answering.


RE: How Right? - Gribouillis - Nov-16-2018

Using 'or' is perfectly OK in python. A or B returns A if bool(A) evaluates to True, otherwise it returns B.
>>> 'spam' or 'eggs'
'spam'
>>> None or 'eggs'
'eggs'
>>> 0 or 'eggs'
'eggs'
>>> [] or 'eggs'
'eggs'
>>> [] or 0
0
If you want 'DEFAULT' only when the key is not in the dictionary, you can write
variable = dict_.get('var_name', 'DEFAULT')



RE: How Right? - Cassie - Nov-16-2018

(Nov-16-2018, 11:15 AM)Gribouillis Wrote: Using 'or' is perfectly OK in python. A or B returns A if bool(A) evaluates to True, otherwise it returns B.
>>> 'spam' or 'eggs'
'spam'
>>> None or 'eggs'
'eggs'
>>> 0 or 'eggs'
'eggs'
>>> [] or 'eggs'
'eggs'
>>> [] or 0
0
If you want 'DEFAULT' only when the key is not in the dictionary, you can write
variable = dict_.get('var_name', 'DEFAULT')

Thanks, I appreciate it.


RE: How Right? - wavic - Nov-16-2018

The expression dict_.get('var_name') or 'DEFAULT' always evaluates to True because of the 'DEFAULT' string. Since it's not an empty string it is True. Add to this the 'or' operator and you get True regardless of what dict_.get(key) returns.