Adding docstrings to namedtuples? Adding docstrings to namedtuples? python python

Adding docstrings to namedtuples?


In Python 3, no wrapper is needed, as the __doc__ attributes of types is writable.

from collections import namedtuplePoint = namedtuple('Point', 'x y')Point.__doc__ = '''\A 2-dimensional coordinatex - the abscissay - the ordinate'''

This closely corresponds to a standard class definition, where the docstring follows the header.

class Point():    '''A 2-dimensional coordinate    x - the abscissa    y - the ordinate'''    <class code>

This does not work in Python 2.

AttributeError: attribute '__doc__' of 'type' objects is not writable.


Came across this old question via Google while wondering the same thing.

Just wanted to point out that you can tidy it up even more by calling namedtuple() right from the class declaration:

from collections import namedtupleclass Point(namedtuple('Point', 'x y')):    """Here is the docstring."""


You can achieve this by creating a simple, empty wrapper class around the returned value from namedtuple. Contents of a file I created (nt.py):

from collections import namedtuplePoint_ = namedtuple("Point", ["x", "y"])class Point(Point_):    """ A point in 2d space """    pass

Then in the Python REPL:

>>> print nt.Point.__doc__ A point in 2d space 

Or you could do:

>>> help(nt.Point)  # which outputs...
Help on class Point in module nt:class Point(Point) |  A point in 2d space |   |  Method resolution order: |      Point |      Point |      __builtin__.tuple |      __builtin__.object ...

If you don't like doing that by hand every time, it's trivial to write a sort-of factory function to do this:

def NamedTupleWithDocstring(docstring, *ntargs):    nt = namedtuple(*ntargs)    class NT(nt):        __doc__ = docstring    return NTPoint3D = NamedTupleWithDocstring("A point in 3d space", "Point3d", ["x", "y", "z"])p3 = Point3D(1,2,3)print p3.__doc__

which outputs:

A point in 3d space