【发布时间】:2014-12-21 11:54:24
【问题描述】:
这段摘自 Python doc。它的文档字符串说函数是non-blocking(例如# non-blocking dict iterator),这就是我不明白的地方。
def iter_except(func, exception, first=None):
""" Call a function repeatedly until an exception is raised.
Converts a call-until-exception interface to an iterator interface.
Like builtins.iter(func, sentinel) but uses an exception instead
of a sentinel to end the loop.
Examples:
iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator
iter_except(d.popitem, KeyError) # non-blocking dict iterator
iter_except(d.popleft, IndexError) # non-blocking deque iterator
iter_except(q.get_nowait, Queue.Empty) # loop over a producer Queue
iter_except(s.pop, KeyError) # non-blocking set iterator
"""
try:
if first is not None:
yield first() # For database APIs needing an initial cast to db.first()
while 1:
yield func()
except exception:
pass
在我看来,generator function 与 iter() 做同样的事情。
据我所知,non-blocking 表示异步或并行计算,或者当您在 multi-thread 中摆脱 lock 时。
sn-p 处于同步执行状态。 non-blocking 这里是什么意思?
【问题讨论】:
-
我想他们的意思是
d可以在迭代期间被其他代码更改,所以这个函数不会“阻止”它。使用iter和更改底层容器可能会导致不可预知的结果。
标签: python generator nonblocking coroutine