0% found this document useful (0 votes)
33 views10 pages

PEP 257 - Docstring Conventions

PEP 257 outlines the conventions and semantics for Python docstrings, aiming to standardize their structure and content. It specifies that all modules, functions, and classes should include docstrings, detailing their behavior, arguments, and return values. The document emphasizes the importance of following these conventions for maintainability and clarity in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views10 pages

PEP 257 - Docstring Conventions

PEP 257 outlines the conventions and semantics for Python docstrings, aiming to standardize their structure and content. It specifies that all modules, functions, and classes should include docstrings, detailing their behavior, arguments, and return values. The document emphasizes the importance of following these conventions for maintainability and clarity in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.

org

PEP 257 – Docstring Conventions

Author: David Goodger <goodger at python.org>, Guido van Rossum <guido at


python.org>
Discussions-To: Doc-SIG list
Status: Active
Type: Informational
Created: 29-May-2001
Post-History: 13-Jun-2001

Abstract

This PEP documents the semantics and conventions associated with Python docstrings.

Rationale

El objetivo de este PEP es estandarizar la estructura de alto nivel de docstrings: qué deben
contener y cómo decirlo (sin tocar cualquier sintaxis de marcado dentro de docstrings). El PEP
contiene convenciones, no leyes o sintaxis.

https://peps.python.org/pep-0257/#what-is-a-docstring 1/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

“Una convención universal proporciona toda la mantenibilidad, claridad, y


consistencia y una base para buenos hábitos de programación también. Lo que
no hace es insistir en que lo sigas en contra de tu voluntad. Eso es Python!”

—Tim Peters en comp.lang.python, 2001-06-16

Si violas estas convenciones, lo peor que obtendrás es algo sucio mira. Pero algún software
(como el Docutil procesamiento docstring sistema PEP 256, PEP 258) estará al tanto de las
convenciones, por lo que seguirlas te dará los mejores resultados.

Especificación

¿Qué es un Docstring?

Un docstring es un literal de cadena que ocurre como la primera declaración en una


definición de módulo, función, clase o método. Tal docstring se convierte en el __doc__
atributo especial de ese objeto.

Todos los módulos deben tener normalmente docstrings, y todas las funciones y las clases
exportadas por un módulo también deben tener docstrings. Público métodos (incluyendo el
__init__ constructor) también debe tener docstrings. Un paquete puede documentarse en la
cadena de documentos del módulo de el __init__.py archivo en el directorio de paquetes.

https://peps.python.org/pep-0257/#what-is-a-docstring 2/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

Los literales de cadena que ocurren en otras partes del código Python también pueden actuar
como documentación. No son reconocidos por el bytecode de Python compilador y no son
accesibles como atributos de objeto de tiempo de ejecución (es decir, no asignado a __doc__ ),
pero dos tipos de docstrings adicionales pueden ser extraído por herramientas de software:

1. Literales de cuerda que ocurren inmediatamente después de una simple asignación en


el nivel superior de un módulo, clase o __init__ se llama método “atributo docstrings”.
2. Los literales de cadena que ocurren inmediatamente después de otra cadena de
documentos son llamado “docstrings” adicional.

Por favor vea PEP 258, “Docutils Design Specification”, para un descripción detallada del
atributo y docstrings adicionales.

Para mayor consistencia, siempre use alrededor docstrings. Usar si usas alguno retrocesos en
tus docstrings. """triple double quotes""" r"""raw triple double quotes"""

Hay dos formas de docstrings: de una línea y de varias líneas docstrings.

Docstrings de una línea

Las frases son para casos realmente obvios. Realmente deberían encajar una línea. Por
ejemplo:

https://peps.python.org/pep-0257/#what-is-a-docstring 3/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root
...

Notas:

Se usan citas triples a pesar de que la cadena se ajusta en una línea. Esto facilita su
posterior expansión.

The closing quotes are on the same line as the opening quotes. This looks better for
one-liners.

There’s no blank line either before or after the docstring.

The docstring is a phrase ending in a period. It prescribes the function or method’s


effect as a command (“Do this”, “Return that”), not as a description; e.g. don’t write
“Returns the pathname …”.

The one-line docstring should NOT be a “signature” reiterating the function/method


parameters (which can be obtained by introspection). Don’t do:

def function(a, b):


"""function(a, b) -> list"""

https://peps.python.org/pep-0257/#what-is-a-docstring 4/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

This type of docstring is only appropriate for C functions (such as built-ins), where
introspection is not possible. However, the nature of the return value cannot be
determined by introspection, so it should be mentioned. The preferred form for such a
docstring would be something like:

def function(a, b):


"""Do X and return a list."""

(Of course “Do X” should be replaced by a useful description!)

Multi-line Docstrings

Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a
blank line, followed by a more elaborate description. The summary line may be used by
automatic indexing tools; it is important that it fits on one line and is separated from the rest
of the docstring by a blank line. The summary line may be on the same line as the opening
quotes or on the next line. The entire docstring is indented the same as the quotes at its first
line (see example below).

Insert a blank line after all docstrings (one-line or multi-line) that document a class –
generally speaking, the class’s methods are separated from each other by a single blank line,
and the docstring needs to be offset from the first method by a blank line.

The docstring of a script (a stand-alone program) should be usable as its “usage” message,
printed when the script is invoked with incorrect or missing arguments (or perhaps with a “-h”
option, for “help”). Such a docstring should document the script’s function and command line

https://peps.python.org/pep-0257/#what-is-a-docstring 5/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

syntax, environment variables, and files. Usage messages can be fairly elaborate (several
screens full) and should be sufficient for a new user to use the command properly, as well as
a complete quick reference 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 by the module, with a one-line summary of each. (These
summaries generally give less detail than the summary line in the object’s docstring.) The
docstring for a package (i.e., the docstring of the package’s __init__.py module) should also
list the modules and subpackages exported by the package.

The docstring for a function or method should summarize its behavior and document its
arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be
called (all if applicable). Optional arguments should be indicated. It should be documented
whether keyword arguments are part of the interface.

The docstring for a class should summarize its behavior and list the public methods and
instance variables. If the class is intended to be subclassed, and has an additional interface for
subclasses, this interface should be listed separately (in the docstring). The class constructor
should be documented in the docstring for its __init__ method. Individual methods should
be documented by their own docstring.

If a class subclasses another class and its behavior is mostly inherited from that class, its
docstring should mention this and summarize the differences. Use the verb “override” to
indicate that a subclass method replaces a superclass method and does not call the

https://peps.python.org/pep-0257/#what-is-a-docstring 6/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

superclass method; use the verb “extend” to indicate that a subclass method calls the
superclass method (in addition to its own behavior).

Do not use the Emacs convention of mentioning the arguments of functions or methods in
upper case in running text. Python is case sensitive and the argument names can be used for
keyword arguments, so the docstring should document the correct argument names. It is
best to list each argument on a separate line. For example:

def complex(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)
"""
if imag == 0.0 and real == 0.0:
return complex_zero
...

Unless the entire docstring fits on a line, place the closing quotes on a line by themselves.
This way, Emacs’ fill-paragraph command can be used on it.

Handling Docstring Indentation

Docstring processing tools will strip a uniform amount of indentation from the second and
further lines of the docstring, equal to the minimum indentation of all non-blank lines after
the first line. Any indentation in the first line of the docstring (i.e., up to the first newline) is

https://peps.python.org/pep-0257/#what-is-a-docstring 7/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

insignificant and removed. Relative indentation of later lines in the docstring is retained. Blank
lines should be removed from the beginning and end of the docstring.

Since code is much more precise than words, here is an implementation of the algorithm:

def trim(docstring):
if not docstring:
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.maxsize
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxsize:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)

The docstring in this example contains two newline characters and is therefore 3 lines long.
The first and last lines are blank:

https://peps.python.org/pep-0257/#what-is-a-docstring 8/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

def foo():
"""
This is the second line of the docstring.
"""

To illustrate:

>>> print repr(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:

def foo():
"""A multi-line
docstring.
"""

def bar():
"""
A multi-line
docstring.
"""

Copyright

This document has been placed in the public domain.

https://peps.python.org/pep-0257/#what-is-a-docstring 9/10
10/4/25, 11:42 PEP 257 – Docstring Conventions | peps.python.org

Acknowledgements

El texto “Specification” viene principalmente textualmente de PEP 8 por Guido van Rossum.

Este documento toma prestadas ideas de los archivos de Python Doc-SIG. Gracias a todos los
miembros pasados y presentes.

Fuente: https://github.com/python/peps/blob/main/peps/pep-0257.rst

Última modificación: 2024-04-17 11:35:59 GMT

https://peps.python.org/pep-0257/#what-is-a-docstring 10/10

You might also like