Comment on Python Performance: Why 'if not list' is 2x Faster Than Using len()
LegoBrickOnFire@lemmy.world 2 days agoWell, in your case it is not clear whether you intended to branch in the variable foo being None, or on the list being empty which is semantically very different…
Thats why it’s better to explicitelly express whether you want an empty collection (len = 0) or a None value.
sugar_in_your_tea@sh.itjust.works 2 days ago
Well yeah, because I’m explicitly not defining a difference between
None
and[]
. In most cases, the difference doesn’t matter.If I did want to differentiate, I’d use another
if
block:Explicit is better than implicit. I hate relying on exceptions like
len(foo) == 0
raising aTypeError
because that’s very much not explicit.Exceptions should be for exceptional cases, as in, things that aren’t expected. If it is expected, make an explicit check for it.
LegoBrickOnFire@lemmy.world 2 days ago
I don’t really understand the point about exceptions. Yeah “not foo” cannot throw an exception. But the program should crash if an invalid input is provided. If the function expects an optional[list] it should be provided with either a list or None, nothing else.
sugar_in_your_tea@sh.itjust.works 2 days ago
Sure. But is
None
invalid input in your case, whereas[]
is valid? If so, make that check explicit, don’t rely on an implicit check thatlen(…)
does.When I see
TypeError
in the logs, I assume the developer screwed up. When I seeValueError
in the logs, I assume the user screwed up. Ideally,TypeError
should never happen, and every case where it could happen should transform it to another type of exception that indicates where the error actually lies.The only exceptions I want to see in my code are:
Implicit ones like accessing attributes on
None
or calling methods that don’t exist shouldn’t be happening in production code.LegoBrickOnFire@lemmy.world 2 days ago
I agree. So if None is a valid input we should check it first, and then check if the length is zero. In this situation, we see a type error only if the programmer screwed up and everything is explicit