Skip to content Skip to sidebar Skip to footer

Why Can't You Toggle A Function Generator's Behavior By An Argument?

Consider these two functions: def foo(): x = 0 while True: yield x x += 1 def wrap_foo(limit=10, gen=True): fg = foo() count = 0 if gen:

Solution 1:

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:

defwrap_foo(limit=10, gen=True):
    fg = foo()
    if gen:
        return (next(fg) for _ inrange(limit))
    else:
        return [next(fg) for _ inrange(limit)]

Solution 2:

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

Why is this?

Because Python can't wait until the function actually executes a yield to decide whether it's a generator. First, generators are defined to not execute any of their code until the first next. Second, a generator might never actually reach any of its yield statements, if it happens to not generate any elements.

Post a Comment for "Why Can't You Toggle A Function Generator's Behavior By An Argument?"