为什么不能通过参数切换函数生成器的行为? [英] Why can't you toggle a function generator's behavior by an argument?
问题描述
请考虑以下两个功能:
def foo():
x = 0
while True:
yield x
x += 1
def wrap_foo(limit=10, gen=True):
fg = foo()
count = 0
if gen:
while count < limit:
yield next(fg)
count += 1
else:
return [next(fg) for _ in range(limit)]=
foo()
是一个生成器,而wrap_foo()
只是限制了生成多少数据.我正在尝试让包装器充当gen=True
的生成器,或充当将所有生成的数据直接通过kwarg gen=False
放入内存的常规函数.
foo()
is a generator, and wrap_foo()
just puts a limit on how much data gets generated. I was experimenting with having the wrapper behave as a generator with gen=True
, or as a regular function that puts all generated data into memory directly with the kwarg gen=False
.
常规生成器行为符合我的预期:
The regular generator behavior works as I'd expect:
In [1352]: [_ for _ in wrap_foo(gen=True)]
Out[1352]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
但是,使用gen=False
不会生成任何内容.
However, with gen=False
, nothing gets generated.
In [1351]: [num for num in wrap_foo(gen=False)]
Out[1351]: []
Python似乎根据yield
语句的存在将函数预分类为生成器(如果注释了yield
,则该示例可以很好地工作).
It seems like Python pre-classifies the function as a generator based on the presence of the yield
statement (latter example works perfectly if yield
is commented out).
这是为什么?我想了解这里的作用机制.我正在运行3.6
Why is this? I would like to understand the mechanisms at play here. I'm running 3.6
推荐答案
Python似乎根据yield语句的存在将函数预分类为生成器
It seems like Python pre-classifies the function as a generator based on the presence of the yield statement
是的,这正是发生的情况. wrap_foo
在函数定义时被确定为生成器.您可以考虑改用生成器表达式:
Yes, that's exactly what happens. wrap_foo
is determined to be a generator at function definition time. You could consider using generator expressions instead:
def wrap_foo(limit=10, gen=True):
fg = foo()
if gen:
return (next(fg) for _ in range(limit))
else:
return [next(fg) for _ in range(limit)]
这篇关于为什么不能通过参数切换函数生成器的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!