Generator metadata/attributes

acooke.org at gmail.com acooke.org at gmail.com
Thu Jan 8 03:46:55 CET 2009


Hi,

(I searched back and found some previous discussion on generator
attributes that seemed to be related to callable generators - this is
NOT that, as far as I can tell)

I want to associate some data with a generator.  This is in a
decorator function, as it happens; the generator is being returned and
I want to add some info that is useful for debugging later.  I have
tried modifying both .__doc__ and an arbitrary attribute, but the
first is read-only, and the second does not exist (ie you cant just
add one by writing to it; same error with setattr).

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)
    # none of these work
    generator.__doc__ = 'From ' + str(self)
    generator.description = 'From ' + str(self)
    setattr(generator, 'description', 'From ' + str(self))
    return generator
  return decorate

and it's used like:

class ...
  @mydeocrator
  def foo(self, ...):
    yield...

Thanks,
Andrew



More information about the Python-list mailing list