There is such a question, how to elegantly implement a function, when the parameter limit is 0, use infinite iteration, when the limit is greater than 0, finite iteration:

Directly reveal the results:

 from loguru import logger
from itertools import count


def func(limit: int = 0):
    for i in limit and range(limit) or count():
        yield i


for i in func():
    logger.debug(i)

If you don't understand the syntax of this limit and range(limit) or count() , you can look at the official documentation first: Boolean operations--- and, or, not

图片.png

Let's parse this grammar a little bit:

When limit is 0, let's see what happens:

 In [8]: limit=0

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

It can be seen that when the limit is not established, the result of limit and range(limit) is the limit

 In [12]: from itertools import count

In [13]: 0 or count()
Out[13]: count(0)

When limit is established, limit and range(limit) are the latter

 In [14]: limit=10

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

universe_king
3.4k 声望680 粉丝