Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How Right?
#1
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.
Reply
#2
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')
Reply
#3
(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.
Reply
#4
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020