Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to put a docstring on Python property?

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.

like image 329
Paul Draper Avatar asked Apr 15 '13 22:04

Paul Draper


People also ask

Which is the correct location to place a docstring for a function?

A docstring is a string literal placed in the first line of a function body, as shown below.

How do you make a good Python docstring?

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.

How is a docstring represented in Python?

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.

What is the standard Python docstring format?

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.


1 Answers

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() 
like image 174
Ben Hoyt Avatar answered Sep 22 '22 08:09

Ben Hoyt