My point is that if your variable can be None then you need the same pattern for the length check.
So for the Pythonic version:
if (foo is not None) and not foo: ...
For the explicit length check:
if (foo is not None) and (len(foo) == 0): ...
Honestly you’re probably better off using type hints and catching such things with static checks and not adding the None check.
sugar_in_your_tea@sh.itjust.works 7 months ago
I don’t see it that way. If you’re doing
if len(foo) == 0, you’re implying thatfoois expected to not beNone, and expecting an exception should not be the default assumption, because exceptions should be… exceptional.Here’s what I assume:
if foo is not None- empty values are explicitly acceptableif not foo- the difference between an empty andNonevalue isn’t importantif len(foo) == 0- implicit assumption thatfoois notNone(I frequently forget thatlen(…)raises onNone)If an exception was intended by the last bullet point, I prefer an explicit raise:
I actually use schema validation to enforce this at the edge so the rest of my code can make reasonable assumptions, and I’m explicit about whether each field may or may not be
None.