method-to-instance binding, callable generator decorator

Emile van Sebille emile at fenx.com
Wed Jan 26 12:28:20 EST 2011


On 1/26/2011 9:04 AM Jack Bates said...
> Am struggling to understand Python method-to-instance binding
>
> Anyone know why this example throws a TypeError?
>
>> >  #!/usr/bin/env python
>> >
>> >  import functools
>> >
>> >  # Take a generator function (i.e. a callable which returns a generator) and
>> >  # return a callable which calls .send()
>> >  class coroutine:
>> >     def __init__(self, function):
>> >       self.function = function
>> >
>> >       functools.update_wrapper(self, function)
>> >
>> >     def __call__(self, *args, **kwds):
>> >       try:
>> >         return self.generator.send(args)
>> >
>> >       except AttributeError:
>> >         self.generator = self.function(*args, **kwds)
>> >
>> >         return self.generator.next()
>> >
>> >  # Each time we're called, advance to next yield
>> >  @coroutine
>> >  def test():
>> >     yield 'call me once'
>> >     yield 'call me twice'

define test

>> >
>> >  # Works like a charm : )
>> >  assert 'call me once' == test()
>> >  assert 'call me twice' == test()
>> >
>> >  class Test:
>> >
>> >     # Each time we're called, advance to next yield
>> >     @coroutine
>> >     def test(self):
>> >       yield 'call me once'
>> >       yield 'call me twice'
>> >
>> >  test = Test()

I'm not sure, but you've shadowed the test function above here.


>> >
>> >  # TypeError, WTF?
>> >  assert 'call me once' == test.test()
>> >  assert 'call me twice' == test.test()
> https://gist.github.com/797019
>
> Am trying to write a decorator such that each time I call a function, it
> advances to the next "yield" - I plan to use functions like this as
> fixtures in tests
>
> Does a decorator like this already exist in the Python standard library?





More information about the Python-list mailing list