Adding docstrings to namedtuples?

前端 未结 10 1529
死守一世寂寞
死守一世寂寞 2020-12-08 01:52

Is it possible to add a documentation string to a namedtuple in an easy manner?

I tried

from collections import namedtuple

Point = namedtuple(\"Poin         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 02:05

    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 namedtuple
    
    Point_ = 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 NT
    
    Point3D = 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
    

提交回复
热议问题