method-to-instance binding, callable generator decorator

J

Jack Bates

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top