为什么 len(None) 不返回 0? [英] Why doesn't len(None) return 0?
问题描述
None
在 Python 中是一个对象.
因此它可以使用 __str__() 之类的函数
<预><代码>>>>字符串(无)'没有任何'但为什么它不为 __len__() 做同样的事情?
<预><代码>>>>len(无)回溯(最近一次调用最后一次):文件<pyshell#3>",第 1 行,在 <module> 中len(无)类型错误:NoneType"类型的对象没有 len()它似乎是 Pythonic,就像 if list
是可接受的一样,即使变量是 None
而不仅仅是一个空列表.
是否存在会使 len(None)
的使用更成问题的情况?
你提到你想要这个:
<块引用>因为当函数返回 None
而不是列表时,它经常作为错误出现
大概,你有这样的代码:
list_probably = some_function()对于范围内的索引(len(list_probably)):...
并且正在得到:
TypeError: 'NoneType' 类型的对象没有 len()
注意以下几点:
len
用于确定 collections 的长度(例如list
、dict
或str
- 这些是Sized
对象).它不是用于将任意对象转换为整数 - 例如,它也没有为int
或bool
实现;- 如果
None
是可能的,您应该明确测试if list_probably is not None
.使用例如if list_probably
会将None
和空列表[]
视为相同,这可能不是正确的行为;和 - 通常有更好的方法来处理
range(len(...))
的列表 - 例如对于list_probably中的项目
,使用zip
等
为 None
实现 len
只会隐藏错误,其中 None
被错误地处理,就像其他错误一样对象 - 根据 Python 之禅(import this
):
错误不应该无声无息地传递.
同样,for item in None
会失败,但这并不意味着实现 None.__iter__
是个好主意!错误是一件好事 - 它们可以帮助您快速找到程序中的问题.
None
in Python is an object.
>>> isinstance(None, object)
True
And as such it can employ functions like __str__()
>>> str(None)
'None'
But why doesn't it do the same for __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 like it would be Pythonic the same way that if list
is acceptable even if the variable is None
and not just an empty list.
Are there cases that would make the use of len(None)
more of a problem?
You mention that you want this:
because it comes up often as an error when a function returns
None
instead of a list
Presumably, you have code like:
list_probably = some_function()
for index in range(len(list_probably)):
...
and are getting:
TypeError: object of type 'NoneType' has no len()
Note the following:
len
is for determining the length of collections (e.g. alist
,dict
orstr
- these areSized
objects). It's not for converting arbitrary objects to integers - it also isn't implemented forint
orbool
, for example;- If
None
is a possibility, you should be explicitly testingif list_probably is not None
. Using e.g.if list_probably
would treatNone
and the empty list[]
the same, which is probably not the correct behaviour; and - There is usually a better way to deal with lists that
range(len(...))
- e.g.for item in list_probably
, usingzip
, etc.
Implementing len
for None
would just hide errors where None
is being treated, incorrectly, like some other object - per the Zen of Python (import this
):
Errors should never pass silently.
Similarly for item in None
would fail, but that doesn't mean that implementing None.__iter__
is a good idea! Errors are a good thing - they help you find the problems in your programs quickly.
这篇关于为什么 len(None) 不返回 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!