Generator metadata/attributes

Rob Williscroft rtw at freenet.co.uk
Wed Jan 7 23:18:19 EST 2009


 wrote in news:d301c93a-8a73-4cbb-9601-fe0c18a94f97
@v5g2000prm.googlegroups.com 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 ):
  @mydecorator
  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.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/



More information about the Python-list mailing list