Generator metadata/attributes

Jeff McNeil jeff at jmcneil.net
Wed Jan 7 22:57:17 EST 2009


You'll see the same behavior if you attempt to add an attribute to an
instance of object as well.

>>> object().t = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 't'
>>>

You'll have to build your own iterator or wrap the generator object
and delegate calls to it. If you elect the latter, you should also
ensure that send and throw and gang work properly.  Perhaps something
nice and thin using getattr within your wrapper class.

Jeff

On Jan 7, 9:46 pm, acooke.... at gmail.com wrote:
> 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