On Aug 15, 3:37 pm, "Marshall T. Vandegrift" <[EMAIL PROTECTED]> wrote: > Bjoern Schliessmann <[EMAIL PROTECTED]> writes: > >> I'm trying to write a decorator which allows one to produce simple > >> coroutines by just writing a function as a generator expression > >> which re-receives it's arguments as a tuple from each yield. > > > May I ask why? Passing it the same arguments over and over is no > > use; and there is the send method. > > That's what I meant. The wrapper produced by the decorator passes the > arguments back into the generator as a tuple via the `send' method. > > >> The ugliness of the ArgPacker class makes me suspect that I should > >> perhaps just manually create and track a generator when I need a > >> function with generator-like properties. > > > What do you mean? I don't quite understand why you'd have to "track" > > a generator for getting generator-like properties. > > Using the trivial `nextn' example from my original post with my > decorator lets you do just: > > print nextn(2) # => [0, 1] > print nextn(3) # => [2, 3, 4] > print nextn() # => [5] > > Without the decorator that becomes: > > gen = nextn(2) > print gen.next() # => [0, 1] > print gen.send(3) # => [2, 3, 4] > print gen.send(1) # => [5] > > The former is just that smidgen nicer, and allows you to continue to > make use of argument defaults and varadic arguments if so desired. >
Do you really need a generator or co-routine to do this? Maybe you can just use a closure: import itertools class Foo(object): it = itertools.count(0) def __call__(self): return self.y def __init__(self, n=1): self.y = [ Foo.it.next() for each in xrange(n) ] def nextn(n=1): return Foo(n)() print nextn() print nextn(3) print nextn(n=2) print nextn() -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list