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?
All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.
@Antimony: pickle handles namedtuple classes just fine; classes defined in a function local namespace not so much.
Moreover, as namedtuple instances do not have per-instance dictionaries, they are lightweight and require no more memory than regular tuples. This makes them faster than dictionaries.
Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field. In this case, we have to use another private method _replace() to replace values of the field. The _replace() method will return a new named tuple.
In Python 3, no wrapper is needed, as the __doc__
attributes of types is writable.
from collections import namedtuple Point = namedtuple('Point', 'x y') Point.__doc__ = '''\ A 2-dimensional coordinate x - the abscissa y - 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 namedtuple class Point(namedtuple('Point', 'x y')): """Here is the docstring."""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With