Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to document fields and properties in Python?

It's easy to document a class or method in Python:

class Something:   """ Description of the class. """    def do_it(self):     """ Description of the method. """     pass    class_variable = 1 # How to comment?    @property   def give_me_some_special_dict(self):     """ doesn't work! Doc of general dict will be shown. """     return {} 

But how to document a field or property for usage in API docs or help?

like image 217
deamon Avatar asked May 19 '11 15:05

deamon


People also ask

What are methods and properties in Python?

The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#. The property() method takes the get, set and delete methods as arguments and returns an object of the property class.

How do you write a class document in Python?

Class method docstrings should contain the following: A brief description of what the method is and what it's used for. Any arguments (both required and optional) that are passed including keyword arguments. Label any arguments that are considered optional or have a default value.

How do you write a Docstring 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.


1 Answers

Python has a PEP (257) that defines Docstring Conventions. Regarding documentation of attributes, it states:

String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called "attribute docstrings".

So the following are considered documented attributes:

class Foo(object):   velocity = 1     """Foo's initial velocity - class variable"""    def __init__(self, args):     self.location = 0.0      """Foo's initial location - instance variable"""    

(Edit: Fixed second docstring)

like image 54
Eli Bendersky Avatar answered Sep 22 '22 02:09

Eli Bendersky