I often struggle with the following if/else syntax and I was hoping some people could give me some of their opinions as to what they think is more clear or if this violates any Pythonisms (I've searched and wasn't able to find anything).
Is one of these better and or right/wrong?
value = None
if 'value' in some_dict:
value = some_dict['value']
some_func(value=value)
OR:
if 'value' in some_dict:
value = some_dict['value']
else:
value = None
some_func(value=value)
OR:
some_func(value=some_dict.get('value', None))
I could see reasons for all.
Of course the last one is the best - described situation is exact case for dict.get
.
Just a note - second parameter to get
is superfluous, you can simply write:
some_func(value=some_dict.get('value'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With