logoalt Hacker News

japhyryesterday at 12:03 PM5 repliesview on HN

Wouldn't this be a little cleaner?

    data = collection.get("key")
    if data:
        ...
    else:
        ...

Replies

pansa2yesterday at 12:13 PM

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.

show 1 reply
blackbear_yesterday at 12:56 PM

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.

Shish2kyesterday at 12:11 PM

That behaves differently (eg if collection["key"] = 0)

IshKebabyesterday at 2:40 PM

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.

tayo42yesterday at 12:10 PM

it depends on what's in the if blocks