Should I make several docstrings, or just one (and where should I put it)?
@property def x(self): return 0 @x.setter def x(self, values): pass
I see that property()
accepts a doc argument.
A docstring is a string literal placed in the first line of a function body, as shown below.
Best practicesAll modules, classes, methods, and functions, including the __init__ constructor in packages should have docstrings. Descriptions are capitalized and have end-of-sentence punctuation. Always use """Triple double quotes.""" around docstrings. Docstrings are not followed by a blank line.
Declaring Docstrings: The docstrings are declared using ”'triple single quotes”' or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.
Nowadays, the probably more prevalent format is the reStructuredText (reST) format that is used by Sphinx to generate documentation. Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). It is also used by default as output format in Pyment.
Write the docstring on the getter, because 1) that's what help(MyClass)
shows, and 2) it's also how it's done in the Python docs -- see the x.setter example.
Regarding 1):
class C(object): @property def x(self): """Get x""" return getattr(self, '_x', 42) @x.setter def x(self, value): """Set x""" self._x = value
And then:
>>> c = C() >>> help(c) Help on C in module __main__ object: class C(__builtin__.object) | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | x | Get x >>>
Note that the setter's docstring "Set x" is ignored.
So you should write the docstring for the entire property (getter and setter) on the getter function for it to be visible. An example of a good property docstring might be:
class Serial(object): @property def baudrate(self): """Get or set the current baudrate. Setting the baudrate to a new value will reconfigure the serial port automatically. """ return self._baudrate @baudrate.setter def baudrate(self, value): if self._baudrate != value: self._baudrate = value self._reconfigure_port()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With