Generator metadata/attributes

Rob Williscroft rtw at
Thu Jan 8 05:18:19 CET 2009

 wrote in news:d301c93a-8a73-4cbb-9601-fe0c18a94f97 in comp.lang.python:

> I realise I could create my own wrapper that implements __next__ (I am
> using Python 3 and haven't checked the exact interface required, but I
> guess it's something like that), and add the information that way, but
> I am worried I am doing something too complicated.  Is there really no
> way to stick some arbitrary data onto a generator (from a function
> that "yield"s)?
> In case it's any help, the decorator is basically:
> def mydecorator(f):
>   def decorate(self, *args):
>     generator = f(self, *args)

You can use something like this:

def mydecorator( f ):
    def decorated(self, *args):
      for i in f(self, *args):
        yield i
    decorated.__doc__ = 'madeup doc string'
    return decorated
class Example( object ):
  def foo(self, a, b, ):
    yield 1
print( help( Example ) )

But realise that when the decorator ("mydecorator" above) is
run neither the class ("Example") or the instance (self) is
available.  Which limits somewhat the debugging information 
you can attach automatically.


More information about the Python-list mailing list