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 1 day ago
I don’t see it that way. If you’re doing
if len(foo) == 0
, you’re implying thatfoo
is 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 andNone
value isn’t importantif len(foo) == 0
- implicit assumption thatfoo
is 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
.