Passing yield as a function argument...
Peter Otten
__peter__ at web.de
Wed May 24 02:08:00 EDT 2017
Christopher Reimer wrote:
> Greetings,
>
> I have two functions that I generalized to be nearly identical except
> for one line. One function has a yield statement, the other function
> appends to a queue.
>
> If I rewrite the one line to be a function passed in as an argument --
> i.e., func(data) -- queue.append works fine. If I create and pass an
> inner function with the yield statement, nothing happens.
>
> Is it possible to pass a yield statement in some form as a function
> argument?
No. A yield expression turns a function into a generator function, and it
does so at compile time:
>>> def f(): pass
...
>>> def g():
... if 0: yield
...
>>> inspect.isgeneratorfunction(f)
False
>>> inspect.isgeneratorfunction(g)
True
Perhaps you can go the other way and write the queue variant in terms of the
generator, something like
def g(...):
for ...:
...
yield ...
def f(...):
for x in g(...):
queue.append(x)
or if your queue supports it just
queue.extend(g(...))
More information about the Python-list
mailing list