有这么一个问题,如何优雅的实现一个函数,当参数 limit 为 0 的时候,应用有限迭代,当 limit 大于 0的时候,无限迭代:

间接解谜后果:

from loguru import loggerfrom itertools import countdef func(limit: int = 0):    for i in limit and range(limit) or count():        yield ifor i in func():    logger.debug(i)

如果你对这个 limit and range(limit) or count() 语法不了解,能够先看看官网文档:布尔运算 --- and, or, not

咱们来一点点解析这个语法:

当 limit 为 0 的时候,咱们来看看是个什么状况吧:

In [8]: limit=0In [9]: limit and range(limit)Out[9]: 0

能够看到,当 limit 不成立的时候,limit and range(limit) 的后果就是 limit

In [12]: from itertools import countIn [13]: 0 or count()Out[13]: count(0)

当 limit 成立的时候,limit and range(limit) 就是后者

In [14]: limit=10In [15]: limit and range(limit)Out[15]: range(0, 10)
In [16]: range(0, 10) or count()Out[16]: range(0, 10)