method-to-instance binding, callable generator decorator

Jack Bates ms419 at freezone.co.uk
Wed Jan 26 12:04:56 EST 2011


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'
> 
> # 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()
> 
> # 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