Generator metadata/attributes

James Stroud jstroud at mbi.ucla.edu
Wed Jan 7 22:14:55 EST 2009


acooke.org 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__ 

That is what you are going to have to do. Immutable python builtins work 
  that way:

py> i = 4
py> i.bob = 2
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.AttributeError'>: 'int' object has no attribute 'bob'

py> i.__doc__ = 'I am an int'
------------------------------------------------------------
Traceback (most recent call last):
   File "<ipython console>", line 1, in <module>
<type 'exceptions.AttributeError'>: 'int' object attribute '__doc__' is 
read-only


James



More information about the Python-list mailing list