python - Why doesn't len(None) return 0? -
none
in python object.
>>> isinstance(none, object) true
and such can employ functions __str__()
>>> str(none) 'none'
but why doesn't same __len__()?
>>> len(none) traceback (most recent call last): file "<pyshell#3>", line 1, in <module> len(none) typeerror: object of type 'nonetype' has no len()
it seems pythonic same way if list
acceptable if variable none
, not empty list.
are there cases make use of len(none)
more of problem?
you mention want this:
because comes error when function returns
none
instead of list
presumably, have code like:
list_probably = some_function() index in range(len(list_probably)): ...
and getting:
typeerror: object of type 'nonetype' has no len()
note following:
len
determining length of collections (e.g.list
,dict
orstr
- thesesized
objects). it's not converting arbitrary objects integers - isn't implementedint
orbool
, example;- if
none
possibility, should explicitly testingif list_probably not none
. using e.g.if list_probably
treatnone
, empty list[]
same, not correct behaviour; and - there better way deal lists
range(len(...))
- e.g.for item in list_probably
, usingzip
, etc.
implementing len
none
hide errors none
being treated, incorrectly, other object - per the zen of python (import this
):
errors should never pass silently.
similarly for item in none
fail, doesn't mean implementing none.__iter__
idea! errors thing - find problems in programs quickly.
Comments
Post a Comment