How does a generator object refer to itself?

Michael ms at cerenity.org
Wed May 24 22:17:47 EDT 2006


Russell wrote:
> The issue is how to write a generator that refers to its own generator
> object. 
> 
> def me():
>     ..
>     nextVal = yield you(me.send)        # This is wrong!

>>> def self_decorate(func):
...    class context:
...        def __init__(self):
...            self.me = None
...        def start(self):
...            self.me = func(self)
...            return self.me
...    return context().start
...
>>> @self_decorate
... def me(self):
...     print "ME!",self.me
...     yield 1
...
>>> me
<bound method context.start of <__main__.context instance at 0x402e940c>>
>>> x=me()
>>> x
<generator object at 0x402e94ac>
>>> x.next()
ME! <generator object at 0x402e94ac>
1

You don't need python 2.5 at all to do this. You do need to have a token
mutable first argument though, as you can see. For more examples of how to
add context to generators in the interests of doing fun and interesting
things loosely coupled, please look at our MiniAxon tutorial here:
   http://kamaelia.sf.net/MiniAxon/

(We don't tend to use decorators though because we'd like our code to run on
Nokia phones as well which use a variant of python 2.2)

For examples of fun things you can do:
   http://kamaelia.sf.net/KamaeliaMacro.html
   http://kamaelia.sf.net/Cookbook.html

Basic approach we're taking is a riff on the idea of Unix Philosophy:
   Write components that do one thing and do it well.
   Write components to work together.
   Write components to handle object streams, because that is a universal
   interface.

... with apologies to Doug McIlroy.

:-)


Michael.




More information about the Python-list mailing list