Adding new methods to an instance with docstrings

Brandon Beck bbeck at
Wed Aug 14 04:16:26 CEST 2002

I'm currently using SPARK ( 
  to help me parse a simple language I'm working on.  Part of the 
novelty of SPARK is that metainformation for the scanner and parser is 
included in the docstrings of the methods you define.

Now to my problem.  I have a bunch of trivial functions I'd like to be 
able to have as part of my scanner, however there are too many of them 
to manually maintain as part of the scanner class.  Instead, I'd like to 
be able to dynamically attach them to my scanner class at runtime.  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?  Is there some other way to add a method to an 
object with a docstring?

Here's the code I'm using:

def add_token(type, attr):
	self.rv.append(Token(type=type, attr=attr))

def add_method(obj, name, attr, doc):
	import new

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


More information about the Python-list mailing list