python中iter是什么意思_iter的用途是什么?

在多处理/多线程代码中,您会(希望)经常会发现这种结构用于轮询队列或管道。在标准库中,您还可以在multiprocessing.Pool中找到:@staticmethod

def _handle_tasks(taskqueue, put, outqueue, pool, cache):

thread = threading.current_thread()

for taskseq, set_length in iter(taskqueue.get, None):

task = None

try:

# iterating taskseq cannot fail

for task in taskseq:

...

else:

util.debug('task handler got sentinel')

不久前,我遇到了this博客条目,我很好地总结了iter(callable, sentinel)相对于{}的优势:Usually, when we iterate over an objects or until a condition happens, we understand the scope of the loop in its first line. e.g., when reading a loop that starts with for book in books we realize we’re iterating over all the books. When we see a loop that starts with while not battery.empty() we realize that the scope of the loop is for as long as we still have battery.

When we say “Do forever” (i.e., while True), it’s obvious that this scope is a lie. So it requires us to hold that thought in our head and search the rest of the code for a statement that’ll get us out of it. We are entering the loop with less information and so it is less readable.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值