Is it possible to add a documentation string to a namedtuple in an easy manner?
I tried
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
"""
A point in 2D space
"""
# Yet another test
"""
A(nother) point in 2D space
"""
Point2 = namedtuple("Point2", ["x", "y"])
print Point.__doc__ # -> "Point(x, y)"
print Point2.__doc__ # -> "Point2(x, y)"
but that doesn't cut it. Is it possible to do in some other way?
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:
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
):Then in the Python REPL:
Or you could do:
If you don't like doing that by hand every time, it's trivial to write a sort-of factory function to do this:
which outputs:
You could concoct your own version of the namedtuple factory function by Raymond Hettinger and add an optional
docstring
argument. However it would be easier -- and arguably better -- to just define your own factory function using the same basic technique as in the recipe. Either way, you'll end up with something reusable.I created this function to quickly create a named tuple and document the tuple along with each of its parameters:
You can then create a new named tuple:
Then instantiate the described named tuple with your own data, ie.
When executing
help(MyTuple)
via the python3 command line the following is shown:Alternatively, you can also specify the parameter's type via:
No, you can only add doc strings to modules, classes and function (including methods)
No need to use a wrapper class as suggested by the accepted answer. Simply literally add a docstring:
This results in: (example using
ipython3
):Voilà!