how to inherit docstrings?

Ethan Furman ethan at stoneleaf.us
Thu Jun 9 12:10:38 EDT 2011


Eric Snow wrote:
> p.s. Am I missing something or can you really not change the docstring
> of a class?  I was thinking about the idea of inheriting class
> docstrings too.

8<--------------------------------------------------------
"""module level docstring"""

def func():
     """function level docstring"""

class Test(object):
     """class level docstring"""
     def meth(self):
         """method level docstring"""


if __name__ == '__main__':
     import sys
     import traceback
     hmmm = (
         sys.modules['__main__'],
         func,
         Test(),
         Test().meth,
         Test,
         Test.meth,
         )
     for obj in hmmm:
         try:
             obj.__doc__ = 'new docstring'
             print('successfully changed %s\n' % obj)
         except:
             traceback.print_exc()
             print()
8<--------------------------------------------------------

Tested from 2.5 - 3.2.  The first three always work, the last one works 
in 3.1+, the fourth and fifth always fail.

-----------------actual output for 2.5--------------------
successfully changed <module '__main__' from 'docstring.py'>

successfully changed <function func at 0x00A8F570>

successfully changed <__main__.Test object at 0x00A94230>

Traceback (most recent call last):
   File "docstring.py", line 25, in <module>
     obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'instancemethod' objects is not 
writable
()
Traceback (most recent call last):
   File "docstring.py", line 25, in <module>
     obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'type' objects is not writable
()
Traceback (most recent call last):
   File "docstring.py", line 25, in <module>
     obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'instancemethod' objects is not 
writable
()
-----------------actual output for 3.2--------------------
successfully changed <module '__main__' from 'docstring.py'>

successfully changed <function func at 0x00BE6F60>

successfully changed <__main__.Test object at 0x00BFE730>

Traceback (most recent call last):
   File "docstring.py", line 25, in <module>
     obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'method' objects is not writable

Traceback (most recent call last):
   File "docstring.py", line 25, in <module>
     obj.__doc__ = 'new docstring'
AttributeError: attribute '__doc__' of 'type' objects is not writable

successfully changed <function meth at 0x00BE6ED0>
-----------------actual output----------------------------

~Ethan~



More information about the Python-list mailing list