[Python-ideas] PEP 380 alternative: A yielding function
Carl M. Johnson
cmjohnson.mailinglist at gmail.com
Wed Jul 28 06:38:02 CEST 2010
What would this code do:
def yield_if_true(x):
if x:
yield_(x)
def maybe_yield(x):
if calculate_property(x):
yield_if_true(x)
else:
return None
maybe_yield(5)
When maybe_yield(5) is called different things need to happen
depending on whether it’s a function or a generator. If it’s a
generator, it shouldn’t execute calculate_property(x) yet, because
generators don’t execute their contents until someone says
next(maybe_yield(5)) (or maybe_yield(5).next() in Py2.x). On the other
hand, if it’s not a generator but a function, then it should run
calculate_property right away. You could try starting out as a
function and then switching to being a generator if anything that you
call has a call to yield_ inside of it, but that strikes me as
extremely clumsy and complicated, and it could lead to unpleasant
surprises if calculate_property has side-effects.
ISTM there’s no way to do something like PEP-380 without requiring
that some special keyword is used to indicate that the def is creating
a generator and not creating a function. There other directions to
take this besides yield from (for example, we could replace def with
gen or some such and give return a special meaning inside a gen
statement), but to try to do it without any kind of keyword at the
site of the caller means violating "In the face of ambiguity, refuse
the temptation to guess.”
-- Carl Johnson
On Tue, Jul 27, 2010 at 3:19 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Anders J. Munch wrote:
>
>> But suppose you could address the source instead? Suppose you could
>> write yield_if_true in such a way that it did not become a generator
>> despite yielding?
>
> I don't see how this would work. The problem isn't that
> yield_if_true becomes a generator -- it's that the function
> calling yield_if_true *doesn't* become a generator, even
> though it needs to.
>
>> Let's call it 'yield_' , for lack of a
>> better name. The function would yield the nearest generator on the
>> call stack.
>
> But if none of the calling functions have yields anywhere
> else, then they're just ordinary functions, and there is
> *no* generator on the call stack!
>
> --
> Greg
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
More information about the Python-ideas
mailing list