Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding docstrings to namedtuples?

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?

like image 991
Rickard Avatar asked Oct 22 '09 10:10

Rickard


People also ask

Should Python classes have Docstrings?

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.

Can you pickle a Namedtuple?

@Antimony: pickle handles namedtuple classes just fine; classes defined in a function local namespace not so much.

What is an advantage of Namedtuples over dictionaries?

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.

How do I change Namedtuple value?

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.


2 Answers

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.

like image 128
Terry Jan Reedy Avatar answered Nov 09 '22 05:11

Terry Jan Reedy


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.""" 
like image 32
CoupleWavyLines Avatar answered Nov 09 '22 05:11

CoupleWavyLines