循环遍历空迭代器不会引发异常 [英] Loop over empty iterator does not raise exception
问题描述
我使用的是Python 3.6.7.
I am on Python 3.6.7.
我刚刚注意到,在空列表上的for
循环甚至不会循环一次.
经过一番思考,这对我来说很有意义. IE.大小为零(空)的对象上的循环返回零次迭代.
I just noticed that a for
loop over an empty list does not loop even once.
After some thought, that made some sense to me. I.e. a loop over a zero-sized (empty) object returns zero iterations.
iterable = []
for element in iterable:
pass
print(element)
>>> NameError: name 'element' is not defined
这意味着如果len(iterable) == 0
,则不会在循环内执行测试.
This means that a test inside the loop will not be executed if len(iterable) == 0
.
iterable = []
for element in iterable:
assert isinstance(element, int)
#nothing happens
那我该如何捕捉到这种情况?
Then how can I catch this situation?
当由于iterable为空而导致我的循环不运行时,是否存在一种紧凑的内置方法来引发错误?
Is there a compact built-in way to raise an error when my loop does not run because the iterable is empty?
要适应这种特殊情况,需要手动进行:
Catching this particular situation requires manually:
- 在循环之前测试
iterator
是否为非空 - 在循环后测试元素是否已定义.两者都不 方法对我来说似乎很优雅
- testing that the
iterator
is non-empty before the loop - testing that the element was defined, after the loop. Neither method seems elegant to me
我可能最终在每个for
循环中都要进行此测试.
And I may end up having this test in every single for
loop.
assert len(iterable) > 0
#loop
或
#loop
assert "element" in dir() #?