This PEP documents the semantics and conventions associated withPython docstrings.
The aim of this PEP is to standardize the high-level structure ofdocstrings: what they should contain, and how to say it (withouttouching on any markup syntax within docstrings). The PEP containsconventions, not laws or syntax.
“A universal convention supplies all of maintainability, clarity,consistency, and a foundation for good programming habits too.What it doesn’t do is insist that you follow it against your will.That’s Python!”—Tim Peters on comp.lang.python, 2001-06-16
If you violate these conventions, the worst you’ll get is some dirtylooks. But some software (such as theDocutils docstring processingsystemPEP 256,PEP 258) will be aware of the conventions, so following themwill get you the best results.
A docstring is a string literal that occurs as the first statement ina module, function, class, or method definition. Such a docstringbecomes the__doc__ special attribute of that object.
All modules should normally have docstrings, and all functions andclasses exported by a module should also have docstrings. Publicmethods (including the__init__ constructor) should also havedocstrings. A package may be documented in the module docstring ofthe__init__.py file in the package directory.
String literals occurring elsewhere in Python code may also act asdocumentation. They are not recognized by the Python bytecodecompiler and are not accessible as runtime object attributes (i.e. notassigned to__doc__), but two types of extra docstrings may beextracted by software tools:
__init__ method are called“attribute docstrings”.Please seePEP 258, “Docutils Design Specification”, for adetailed description of attribute and additional docstrings.
For consistency, always use"""tripledoublequotes""" arounddocstrings. User"""rawtripledoublequotes""" if you use anybackslashes in your docstrings.
There are two forms of docstrings: one-liners and multi-linedocstrings.
One-liners are for really obvious cases. They should really fit onone line. For example:
defkos_root():"""Return the pathname of the KOS root directory."""global_kos_rootif_kos_root:return_kos_root...
Notes:
deffunction(a,b):"""function(a, b) -> list"""
This type of docstring is only appropriate for C functions (such asbuilt-ins), where introspection is not possible. However, thenature of thereturn value cannot be determined by introspection,so it should be mentioned. The preferred form for such a docstringwould be something like:
deffunction(a,b):"""Do X and return a list."""
(Of course “Do X” should be replaced by a useful description!)
Multi-line docstrings consist of a summary line just like a one-linedocstring, followed by a blank line, followed by a more elaboratedescription. The summary line may be used by automatic indexingtools; it is important that it fits on one line and is separated fromthe rest of the docstring by a blank line. The summary line may be onthe same line as the opening quotes or on the next line. The entiredocstring is indented the same as the quotes at its first line (seeexample below).
Insert a blank line after all docstrings (one-line or multi-line) thatdocument a class – generally speaking, the class’s methods areseparated from each other by a single blank line, and the docstringneeds to be offset from the first method by a blank line.
The docstring of a script (a stand-alone program) should be usable asits “usage” message, printed when the script is invoked with incorrector missing arguments (or perhaps with a “-h” option, for “help”).Such a docstring should document the script’s function and commandline syntax, environment variables, and files. Usage messages can befairly elaborate (several screens full) and should be sufficient for anew user to use the command properly, as well as a complete quickreference to all options and arguments for the sophisticated user.
The docstring for a module should generally list the classes,exceptions and functions (and any other objects) that are exported bythe module, with a one-line summary of each. (These summariesgenerally give less detail than the summary line in the object’sdocstring.) The docstring for a package (i.e., the docstring of thepackage’s__init__.py module) should also list the modules andsubpackages exported by the package.
The docstring for a function or method should summarize its behaviorand document its arguments, return value(s), side effects, exceptionsraised, and restrictions on when it can be called (all if applicable).Optional arguments should be indicated. It should be documentedwhether keyword arguments are part of the interface.
The docstring for a class should summarize its behavior and list thepublic methods and instance variables. If the class is intended to besubclassed, and has an additional interface for subclasses, thisinterface should be listed separately (in the docstring). The classconstructor should be documented in the docstring for its__init__method. Individual methods should be documented by their owndocstring.
If a class subclasses another class and its behavior is mostlyinherited from that class, its docstring should mention this andsummarize the differences. Use the verb “override” to indicate that asubclass method replaces a superclass method and does not call thesuperclass method; use the verb “extend” to indicate that a subclassmethod calls the superclass method (in addition to its own behavior).
Do not use the Emacs convention of mentioning the arguments offunctions or methods in upper case in running text. Python is casesensitive and the argument names can be used for keyword arguments, sothe docstring should document the correct argument names. It is bestto list each argument on a separate line. For example:
defcomplex(real=0.0,imag=0.0):"""Form a complex number. Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ifimag==0.0andreal==0.0:returncomplex_zero...
Unless the entire docstring fits on a line, place the closing quoteson a line by themselves. This way, Emacs’fill-paragraph commandcan be used on it.
Docstring processing tools will strip a uniform amount of indentationfrom the second and further lines of the docstring, equal to theminimum indentation of all non-blank lines after the first line. Anyindentation in the first line of the docstring (i.e., up to the firstnewline) is insignificant and removed. Relative indentation of laterlines in the docstring is retained. Blank lines should be removedfrom the beginning and end of the docstring.
Since code is much more precise than words, here is an implementationof the algorithm:
deftrim(docstring):ifnotdocstring:return''# Convert tabs to spaces (following the normal Python rules)# and split into a list of lines:lines=docstring.expandtabs().splitlines()# Determine minimum indentation (first line doesn't count):indent=sys.maxsizeforlineinlines[1:]:stripped=line.lstrip()ifstripped:indent=min(indent,len(line)-len(stripped))# Remove indentation (first line is special):trimmed=[lines[0].strip()]ifindent<sys.maxsize:forlineinlines[1:]:trimmed.append(line[indent:].rstrip())# Strip off trailing and leading blank lines:whiletrimmedandnottrimmed[-1]:trimmed.pop()whiletrimmedandnottrimmed[0]:trimmed.pop(0)# Return a single string:return'\n'.join(trimmed)
The docstring in this example contains two newline characters and istherefore 3 lines long. The first and last lines are blank:
deffoo():""" This is the second line of the docstring. """
To illustrate:
>>>printrepr(foo.__doc__)'\n This is the second line of the docstring.\n '>>>foo.__doc__.splitlines()['', ' This is the second line of the docstring.', ' ']>>>trim(foo.__doc__)'This is the second line of the docstring.'
Once trimmed, these docstrings are equivalent:
deffoo():"""A multi-line docstring. """defbar():""" A multi-line docstring. """
This document has been placed in the public domain.
The “Specification” text comes mostly verbatim fromPEP 8by Guido van Rossum.
This document borrows ideas from the archives of the PythonDoc-SIG.Thanks to all members past and present.
Source:https://github.com/python/peps/blob/main/peps/pep-0257.rst
Last modified:2024-04-17 11:35:59 GMT