【问题标题】:Is there a good way to document attributes with `python-attrs`?有没有用`python-attrs`记录属性的好方法?
【发布时间】:2021-12-08 14:20:48
【问题描述】:

我习惯于用文档字符串记录我的__init__() 函数,但我想利用attrs 包的好处。文档字符串在 IPython 或 Jupyter 笔记本中很有用,因此我可以看到参数的含义。有没有好的方法来做到这一点?在此示例代码中:

@atrr.s
class Coordinates(object):
    """ A set of coordinates
    """
    x = attr.ib()
    y = attr.ib()

"""
In [1]: Coordinates?
Init signature: Coordinates(x, y) -> None
Docstring:     
A set of coordinates
    
Init docstring: Method generated by attrs for class Coordinates.
Type:           type
Subclasses:
"""

如何向用户描述xy 变量?例如,如何指定这些以度为单位?

【问题讨论】:

    标签: python python-attrs


    【解决方案1】:

    在 Python 中,属性和(更重要的是)__init__ 参数的文档发生在 class docstring 中,因此在这种情况下 attrs 的存在并不重要:

    @attr.define
    class Coordinates:
        """
        A set of coordinates.
    
        :param int x: Foo in degrees.
        :param int y: Bar in degrees.
        """
        x: int
        y: int
    

    有关更多信息,请查看 RTD 的docs on writing docstrings

    如果你不喜欢这种格式,另一种常见的叫做拿破仑,来自谷歌:https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html

    【讨论】:

    • 我想更多的是numpy style,但你说得很好。他们说__init__ 记录在 Class 文档字符串中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多