Why can't you toggle a function generator's behavior by an argument?

后端 未结 2 1917
北恋
北恋 2021-01-19 12:57

Consider these two functions:

def foo():
    x = 0
    while True:
        yield x
        x += 1

def wrap_foo(limit=10, gen=True):
    fg = foo()
    count         


        
2条回答
  •  -上瘾入骨i
    2021-01-19 13:28

    It seems like Python pre-classifies the function as a generator based on the presence of the yield statement

    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)]
    

提交回复
热议问题