Hwy doesn't len(None) return zero ?
Stefan Behnel
stefan_ml at behnel.de
Wed Jun 30 14:57:53 EDT 2010
Stef Mientki, 30.06.2010 20:39:
> I've lot of functions that returns their result in some kind of tuple / list / array,
> and if there is no result, these functions return None.
> Now I'm often what to do something if I've more than 1 element in the result.
> So I test:
>
> if len ( Result )> 1 :
>
> But to prevent exceptions, i've to write ( I often forget)
> if Result and ( len ( Result )> 1 ) :
>
> So I wonder why len is not allowed on None
> and if there are objections to extend the len function .
Because getting an exception is actually a feature. Imagine a world where
None would implement all sorts of protocols, such as len, getitem, getattr,
etc., and would always return something that would be useful for, well,
someone, maybe even a majority of "use cases". In such a world, it would
actually be very easy to write buggy code that doesn't handle None values
properly, simply because it's easy for programmers to forget to do so. And
this would mean that code that would best drop dead early would instead
silently ignore all errors and just do, well, something, which may or may
not be meaningful, correct and/or useful. That would be very hard to debug
code, as it would fail in obscure places that may be completely unrelated
to the original problem.
The current behaviour, on the other hand, will give you an exception
exactly in the place where you treat the None value in an illegal way, so
it will be easy for you to see what the problem is and much easier to track
it down.
Stefan
More information about the Python-list
mailing list