Comment on Python Performance: Why 'if not list' is 2x Faster Than Using len()
LegoBrickOnFire@lemmy.world 2 days agoI 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
sugar_in_your_tea@sh.itjust.works 2 days ago
Yes. If
None
is just as valid and has the same meaning as[]
for the function (true more often than not), just doif not foo
. IfNone
should be handled separately from[]
for some reason, treat them both separately so it’s absolutely clear.And I especially like this one:
The one obvious way to check if you have data is
if foo
. That works for pretty much everything as you’d expect. Explicitly deviating from that is a cue to the reader that they should pay attention. In this case, that meansNone
is semantically different than empty data, and that’s something the reader should be aware of.LegoBrickOnFire@lemmy.world 2 days ago
I dislike treating None as an equivalent for the empy list, but that does not further the discussion…
I hurt myself in confusion while reading the second quote. Is it the right quote? (also, nazi (relating to the nsdap) is probably not the right word, did you mean fascist?)