[Python-ideas] keyword for introducing generators
Andrew Barnert
abarnert at yahoo.com
Sun Aug 17 00:36:26 CEST 2014
On Aug 16, 2014, at 14:55, Chris Angelico <rosuav at gmail.com> wrote:
> On Sun, Aug 17, 2014 at 7:46 AM, Neil Girdhar <mistersheik at gmail.com> wrote:
>> I'm sure this has been suggested before, but I just spent two days trying to
>> figure out why a method wasn't being called only to find that I'd
>> accidentally pasted a yield into the function. What is the argument against
>> a different keyword for introducing generator functions/methods?
>
> There are quite a few changes to a function based on its body, like
> how the presence of assignment causes a name to be local unless
> explicitly declared otherwise. It's not necessary to predeclare
> everything.
>
> But if you're having trouble with a function like that, maybe a little
> decorator would help:
>
> def announce(f):
> def inner(*a,**kw):
> print("Calling:",f.__name__)
> ret=f(*a,**kw)
> print("Return value is a",type(ret))
> return ret
> return inner
I think it would be both simpler and more useful for him to write:
def generator(f):
assert inspect.isgeneratorfunction(f)
return f
def function(f):
asset not inspect.isgeneratorfunction(f)
return f
Then he can just declare his functions as @generator or @function as appropriate and get an error at definition time if he accidentally got something wrong.
More information about the Python-ideas
mailing list