将docstrings添加到namedtuples?

时间:2009-10-22 10:55:53

标签: python docstring namedtuple

是否可以轻松地将文档字符串添加到namedtuple?

我试过

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)"

但这不会削减它。有可能以其他方式做吗?

10 个答案:

答案 0 :(得分:59)

通过谷歌遇到这个老问题,同时想知道同样的事情。

只是想指出你可以通过从类声明中调用namedtuple()来进一步整理它:

from collections import namedtuple

class Point(namedtuple('Point', 'x y')):
    """Here is the docstring."""

答案 1 :(得分:57)

在Python 3中,不需要包装器,因为类型的__doc__属性是可写的。

from collections import namedtuple

Point = namedtuple('Point', 'x y')
Point.__doc__ = '''\
A 2-dimensional coordinate

x - the abscissa
y - the ordinate'''

这与标准类定义密切对应,其中docstring遵循标题。

class Point():
    '''A 2-dimensional coordinate

    x - the abscissa
    y - the ordinate'''
    <class code>

这在Python 2中不起作用。

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

答案 2 :(得分:46)

您可以通过围绕namedtuple的返回值创建一个简单的空包装类来实现此目的。我创建的文件的内容(nt.py):

from collections import namedtuple

Point_ = namedtuple("Point", ["x", "y"])

class Point(Point_):
    """ A point in 2d space """
    pass

然后在Python REPL中:

>>> print nt.Point.__doc__
 A point in 2d space 

或者你可以这样做:

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

如果你不喜欢每次都用手工做,那么编写一种工厂函数来做这件事是微不足道的:

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__

输出:

A point in 3d space

答案 3 :(得分:26)

  

是否可以轻松地将文档字符串添加到namedtuple?

Python 3

在Python 3中,您可以轻松更改namedtuple上的文档:

NT = collections.namedtuple('NT', 'foo bar')

NT.__doc__ = """:param str foo: foo name
:param list bar: List of bars to bar"""

这使我们可以在调用帮助时查看它们的意图:

Help on class NT in module __main__:

class NT(builtins.tuple)
 |  :param str foo: foo name
 |  :param list bar: List of bars to bar
...

与我们在Python 2中完成同样的事情相比,这非常简单。

Python 2

在Python 2中,您需要

  • 将namedtuple和
  • 子类化
  • 声明__slots__ == ()

声明__slots__ 是另一个在这里回答的重要部分

如果您没有声明__slots__ - 您可以向实例添加可变的ad-hoc属性,从而引入错误。

class Foo(namedtuple('Foo', 'bar')):
    """no __slots__ = ()!!!"""

现在:

>>> f = Foo('bar')
>>> f.bar
'bar'
>>> f.baz = 'what?'
>>> f.__dict__
{'baz': 'what?'}

每个实例都会在访问__dict__时创建单独的__dict__(缺少__slots__否则会阻碍功能,但元组的轻量级,不变性,和声明的属性都是namedtuples的重要特征。

如果您希望在命令行上回显的内容为您提供等效对象,那么您还需要__repr__

NTBase = collections.namedtuple('NTBase', 'foo bar')

class NT(NTBase):
    """
    Individual foo bar, a namedtuple

    :param str foo: foo name
    :param list bar: List of bars to bar
    """
    __slots__ = ()

如果您使用不同的名称创建基本的namedtuple,则需要__repr__这样的代码(就像我们上面使用名称字符串参数'NTBase'所做的那样):

    def __repr__(self):
        return 'NT(foo={0}, bar={1})'.format(
                repr(self.foo), repr(self.bar))

要测试repr,实例化,然后测试传递给eval(repr(instance))

的相等性
nt = NT('foo', 'bar')
assert eval(repr(nt)) == nt

文档中的示例

docs also给出了一个关于__slots__的示例 - 我将自己的文档字符串添加到其中:

class Point(namedtuple('Point', 'x y')):
    """Docstring added here, not in original"""
    __slots__ = ()
    @property
    def hypot(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5
    def __str__(self):
        return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)
     

...

     

上面显示的子类将__slots__设置为空元组。这有帮助   通过阻止实例的创建来保持低内存要求   字典。

这演示了就地使用(如此处建议的另一个答案),但请注意,当您查看方法解析顺序时,就地使用可能会变得混乱,如果您正在调试,这就是我最初的原因建议使用Base作为基本namedtuple的后缀:

>>> Point.mro()
[<class '__main__.Point'>, <class '__main__.Point'>, <type 'tuple'>, <type 'object'>]
                # ^^^^^---------------------^^^^^-- same names!        

要防止在使用它的类中进行子类化时创建__dict__,还必须在子类中声明它。另请参阅this answer for more caveats on using __slots__

答案 4 :(得分:6)

从Python 3.5开始,可以更新namedtuple个对象的文档字符串。

来自whatsnew

Point = namedtuple('Point', ['x', 'y'])
Point.__doc__ += ': Cartesian coodinate'
Point.x.__doc__ = 'abscissa'
Point.y.__doc__ = 'ordinate'

答案 5 :(得分:4)

在Python 3.6+中,您可以使用:

class Point(NamedTuple):
    """
    A point in 2D space
    """
    x: float
    y: float

答案 6 :(得分:3)

无需使用已接受答案建议的包装类。只需字面上添加文档字符串:

from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
Point.__doc__="A point in 2D space"

这导致:(使用ipython3)示例:

In [1]: Point?
Type:       type
String Form:<class '__main__.Point'>
Docstring:  A point in 2D space

In [2]: 

瞧!

答案 7 :(得分:1)

您可以通过Raymond Hettinger编制自己的namedtuple factory function版本,并添加一个可选的docstring参数。然而,使用与配方中相同的基本技术来定义您自己的工厂功能会更容易 - 并且可以说更好。无论哪种方式,你都会得到可重复使用的东西。

from collections import namedtuple

def my_namedtuple(typename, field_names, verbose=False,
                 rename=False, docstring=''):
    '''Returns a new subclass of namedtuple with the supplied
       docstring appended to the default one.

    >>> Point = my_namedtuple('Point', 'x, y', docstring='A point in 2D space')
    >>> print Point.__doc__
    Point(x, y):  A point in 2D space
    '''
    # create a base class and concatenate its docstring and the one passed
    _base = namedtuple(typename, field_names, verbose, rename)
    _docstring = ''.join([_base.__doc__, ':  ', docstring])

    # fill in template to create a no-op subclass with the combined docstring
    template = '''class subclass(_base):
        %(_docstring)r
        pass\n''' % locals()

    # execute code string in a temporary namespace
    namespace = dict(_base=_base, _docstring=_docstring)
    try:
        exec template in namespace
    except SyntaxError, e:
        raise SyntaxError(e.message + ':\n' + template)

    return namespace['subclass']  # subclass object created

答案 8 :(得分:0)

我创建了此函数,以快速创建一个命名的元组并记录该元组及其每个参数:

from collections import namedtuple


def named_tuple(name, description='', **kwargs):
    """
    A named tuple with docstring documentation of each of its parameters
    :param str name: The named tuple's name
    :param str description: The named tuple's description
    :param kwargs: This named tuple's parameters' data with two different ways to describe said parameters. Format:
        <pre>{
            str: ( # The parameter's name
                str, # The parameter's type
                str # The parameter's description
            ),
            str: str, # The parameter's name: the parameter's description
            ... # Any other parameters
        }</pre>
    :return: collections.namedtuple
    """
    parameter_names = list(kwargs.keys())

    result = namedtuple(name, ' '.join(parameter_names))

    # If there are any parameters provided (such that this is not an empty named tuple)
    if len(parameter_names):
        # Add line spacing before describing this named tuple's parameters
        if description is not '':
            description += "\n"

        # Go through each parameter provided and add it to the named tuple's docstring description
        for parameter_name in parameter_names:
            parameter_data = kwargs[parameter_name]

            # Determine whether parameter type is included along with the description or
            # if only a description was provided
            parameter_type = ''
            if isinstance(parameter_data, str):
                parameter_description = parameter_data
            else:
                parameter_type, parameter_description = parameter_data

            description += "\n:param {type}{name}: {description}".format(
                type=parameter_type + ' ' if parameter_type else '',
                name=parameter_name,
                description=parameter_description
            )

            # Change the docstring specific to this parameter
            getattr(result, parameter_name).__doc__ = parameter_description

    # Set the docstring description for the resulting named tuple
    result.__doc__ = description

    return result

然后您可以创建一个新的命名元组:

MyTuple = named_tuple(
    "MyTuple",
    "My named tuple for x,y coordinates",
    x="The x value",
    y="The y value"
)

然后使用您自己的数据实例化所描述的命名元组。

t = MyTuple(4, 8)
print(t) # prints: MyTuple(x=4, y=8)

通过python3命令行执行help(MyTuple)时,显示以下内容:

Help on class MyTuple:

class MyTuple(builtins.tuple)
 |  MyTuple(x, y)
 |
 |  My named tuple for x,y coordinates
 |
 |  :param x: The x value
 |  :param y: The y value
 |
 |  Method resolution order:
 |      MyTuple
 |      builtins.tuple
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __getnewargs__(self)
 |      Return self as a plain tuple.  Used by copy and pickle.
 |
 |  __repr__(self)
 |      Return a nicely formatted representation string
 |
 |  _asdict(self)
 |      Return a new OrderedDict which maps field names to their values.
 |
 |  _replace(_self, **kwds)
 |      Return a new MyTuple object replacing specified fields with new values
 |
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |
 |  _make(iterable) from builtins.type
 |      Make a new MyTuple object from a sequence or iterable
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  __new__(_cls, x, y)
 |      Create new instance of MyTuple(x, y)
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  x
 |      The x value
 |
 |  y
 |      The y value
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  _fields = ('x', 'y')
 |  
 |  _fields_defaults = {}
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from builtins.tuple:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  count(self, value, /)
 |      Return number of occurrences of value.
 |  
 |  index(self, value, start=0, stop=9223372036854775807, /)
 |      Return first index of value.
 |      
 |      Raises ValueError if the value is not present.

或者,您也可以通过以下方式指定参数的类型:

MyTuple = named_tuple(
    "MyTuple",
    "My named tuple for x,y coordinates",
    x=("int", "The x value"),
    y=("int", "The y value")
)

答案 9 :(得分:-2)

不,您只能将文档字符串添加到模块,类和函数(包括方法)