Hacker News new | ask | show | jobs
by IshKebab 179 days ago
You should do normally do

    data = collection.get("key")
    if data is not None:
         ...
    else:
         ....
2 comments

Wouldn't this be a little cleaner?

    data = collection.get("key")
    if data:
        ...
    else:
        ...
If 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.
:facepalm:
No, 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.
No, 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.
That behaves differently (eg if collection["key"] = 0)
it depends on what's in the if blocks
The value in the collection could be the actual value None, that’s different from the collection not having the key.

    missing = object()
    data = collection.get("key", missing)
    if data is missing:
         ...
    else:
         ....
That's why I said "normally".