3 ms·
You should do normally do data = collection.get("key") if data is not None: ... else: ....
by IshKebab 11mo ago
You should do normally do
data = collection.get("key")
if data is not None:
...
else:
....
- japhyr 11mo agoWouldn't this be a little cleaner? data = collection.get("key") if data: ... else: ...
- tayo42 11mo agoit depends on what's in the if blocks
- Shish2k 11mo agoThat behaves differently (eg if collection["key"] = 0)
- pansa2 11mo agoIf valid `data` can be zero, an empty string, or anything else “falsy”, then your version won’t handle those values correctly. It treats them the same as `None`, i.e. not found.
- japhyr 11mo ago:facepalm:
- blackbear_ 11mo agoNo, this would crash with numpy arrays, pandas series and such, with a ValueError: The truth value of an array with more than one element is ambiguous.
- IshKebab 11mo agoNo, truthiness (implicit bool coercion) is another thing you should avoid. This will do weird things if data is a string or a list or whatever.
- echoangle 11mo agoThe value in the collection could be the actual value None, that’s different from the collection not having the key.