Adding new methods to an instance with docstrings

Hans Nowak wurmy at
Wed Aug 14 11:17:09 EDT 2002

Brandon Beck wrote:

> In 
> order for the SPARK framework to be able to use these methods they must 
> have a docstring associated with them.  This is where my trouble lies. I 
> am able to add methods to an object using the instancemethod() function 
> in the new module, however when I attempt to assign to the __doc__ 
> attribute of the new method, I get the following exception:
> AttributeError: 'instance method' object attribute '__doc__' is read-only
> Is there a good reason for having this docstring be read-only while all 
> other docstrings aren't?  

Probably, but I don't know enough about Python's internals to answer that. :)

> Is there some other way to add a method to an 
> object with a docstring?

Instead of a lambda, you could try using a def statement:

>     method = new.instancemethod(lambda attr: add_token('ID', attr), 
> None, obj)
>     method.__doc__ = doc
>     setattr(obj, name, method)

   def dummy(attr):
       """ Your docstring here. """
       return add_token('ID', attr)

   method = new.instancemethod(dummy, None, obj)

I didn't test this code, but you'll get the idea.

By the way, it seems you're adding the method to the class, not to an instance. 
If that is what you want, wouldn't it be easier to do something like:

 >>> class Spam: pass

 >>> def eggs(self, x):
	print x, "eggs on the wall"
 >>> Spam.eggs = eggs
 >>> spam = Spam()
 >>> spam.eggs(4)
4 eggs on the wall



Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter::

More information about the Python-list mailing list