你提到你想要这个:
because it comes up often as an error when a function returns None instead of a list
据推测,你有以下代码:
list_probably = some_function()
for index in range(len(list_probably)):
...
并得到:
TypeError: object of type 'NoneType' has no len()
请注意以下事项:
> len用于确定集合的长度(例如列表,字典或str – 这些是Sized个对象).它不是用于将任意对象转换为整数 – 例如,它也不是为int或bool实现的;
>如果无可能,则应明确测试list_probably是否为None.使用例如如果list_probably会处理None而空列表[]相同,这可能不是正确的行为;和
>通常有一种更好的方法来处理范围(len(…))的列表 – 例如对于list_probably中的项目,使用zip等.
实现len for None只会隐藏错误,其中没有被处理,不正确,就像其他一些对象 – 每the Zen of Python(导入此):
Errors should never pass silently.
同样,对于None中的项目会失败,但这并不意味着实现None .__ iter__是个好主意!错误是一件好事 – 它们可以帮助您快速找到程序中的问题.