if found the following code in some open source lib:
message.get('title', None) or None
is there any reason to do like this instead of message.get('title', None)?
if found the following code in some open source lib:
message.get('title', None) or None
is there any reason to do like this instead of message.get('title', None)?
This will guarantee that any falsy value (e.g. None, '', 0, False, [], ...) in the dict will turn into None. i.e. if you had
d = {'title': False}
then
d.get('title', None) # False
d.get('title', None) or None # None
Whether there is a practical use-case for this is debatable, but there definitely is a subtle difference...
Also note that you could simplify this to:
d.get('title') or None
since d.get defaults to returning None if no element is found.
If you get message and it is a false-y value this will change it to None.
For example
message = {'title' : ''}
message.get('title', None)
>> ''
message.get('title', None) or None
>> None
There is a reason.
For example, message.get('title', None) or None could return an empty string. The boolean value of an empty string in Python is False, so None will be returned instead.
This would also apply to any other value returned from the dict that evaluates to False. None will be returned instead.
Note: However, that code would be better written as message.get('title') or None, because dict.get returns None (the second argument) by default anyways.