sappjw
sappjw

Reputation: 479

Is there a good way to document attributes with `python-attrs`?

I'm used to documenting my __init__() function with a docstring, but I would like to take advantage of the benefits of the attrs package. The docstring is useful in IPython or a Jupyter notebook, so I can see what the parameters mean. Is there a good way to do this? In this example code:

@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:
"""

how can I describe the x and y variables to the user? For example, how can I specify that these are in degrees?

Upvotes: 2

Views: 1166

Answers (1)

hynek
hynek

Reputation: 4116

In Python, the documentation of attributes and (more importantly) __init__ arguments happens in the class docstring, therefore the presence of attrs is not important in this case:

@attr.define
class Coordinates:
    """
    A set of coordinates.

    :param int x: Foo in degrees.
    :param int y: Bar in degrees.
    """
    x: int
    y: int

For more information check out RTD's docs on writing docstrings.

If you don't like this format, another common one is called Napoleon and comes from Google: https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html

Upvotes: 2

Related Questions