What is the dict.get ("..", "No") or "No" script?

if the following code is found in some open source lib:

message.get('title', None) or None 

Is there any reason to do this instead of message.get('title', None) ?

+8
python
source share
3 answers

This ensures that any false value (for example, None , '' , 0 , False , [] , ...) in the dict will turn into None . those. if you have

 d = {'title': False} 

then

 d.get('title', None) # False d.get('title', None) or None # None 

Is there a practical precedent for this debatable, but there is definitely a subtle difference ...


Also note that you can simplify this:

 d.get('title') or None 

since d.get by default returns None if the item is not found.

+16
source share

If you get a message and this value is false-y, it will change it to None.

for example

 message = {'title' : ''} message.get('title', None) >> '' message.get('title', None) or None >> None 
+1
source share

There is a reason.

For example, message.get('title', None) or None may return an empty string. The boolean value of an empty string in Python is False , so None will be returned instead.

This also applies to any other value returned from a dict that evaluates to False . None will be returned.

Note: However, this code is best written as message.get('title') or None , because dict.get always returns None by default (second argument).

-one
source share

All Articles