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 or str - these sized objects). it's not converting arbitrary objects integers - isn't implemented int or bool, example;
  • if none possibility, should explicitly testing if list_probably not none. using e.g. if list_probably treat none , empty list [] same, not correct behaviour; and
  • there better way deal lists range(len(...))- e.g. for item in list_probably, using zip, 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

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -