Adding docstrings to namedtuples?

前端 未结 10 1541
死守一世寂寞
死守一世寂寞 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条回答
  •  旧时难觅i
    2020-12-08 02:05

    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'''
        
    

    This does not work in Python 2.

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

提交回复
热议问题