Cadenas de documentos de Python (con ejemplos)

En este tutorial, aprenderemos sobre las cadenas de documentación de Python. Más específicamente, aprenderemos cómo y por qué se usan cadenas de documentos con la ayuda de ejemplos.

Las cadenas de documentación de Python son los literales de cadena que aparecen justo después de la definición de una función, método, clase o módulo. Pongamos un ejemplo.

Ejemplo 1: cadenas de documentos

 def square(n): '''Takes in a number n, returns the square of n''' return n**2

Aquí, la cadena literal:

 '' 'Toma un número n, devuelve el cuadrado de n' ''

Dentro de las comillas triples se encuentra la cadena de documentación de la función square()tal como aparece justo después de su definición.

Nota: También podemos usar """comillas triples para crear cadenas de documentos.

Comentarios de Python frente a cadenas de documentos

Comentarios de Python

Los comentarios son descripciones que ayudan a los programadores a comprender mejor la intención y la funcionalidad del programa. Son completamente ignorados por el intérprete de Python.

En Python, usamos el símbolo de almohadilla #para escribir un comentario de una sola línea. Por ejemplo,

 # Program to print "Hello World" print("Hello World") 

Comentarios de Python usando cadenas

Si no asignamos cadenas a ninguna variable, actúan como comentarios. Por ejemplo,

 "I am a single-line comment" ''' I am a multi-line comment! ''' print("Hello World")

Nota: utilizamos comillas triples para cadenas de varias líneas.

Cadenas de documentación de Python

Como se mencionó anteriormente, las cadenas de documentación de Python son cadenas que se usan justo después de la definición de una función, método, clase o módulo (como en el Ejemplo 1 ). Se utilizan para documentar nuestro código.

Podemos acceder a estas cadenas de documentos usando el __doc__atributo.

Atributo __doc__ de Python

Siempre que los literales de cadena están presentes justo después de la definición de una función, módulo, clase o método, se asocian con el objeto como su __doc__atributo. Posteriormente, podemos usar este atributo para recuperar esta cadena de documentos.

Ejemplo 2: impresión de una cadena de documentos

 def square(n): '''Takes in a number n, returns the square of n''' return n**2 print(square.__doc__)

Salida

 Toma un número n, devuelve el cuadrado de n

Aquí, square()se puede acceder a la documentación de nuestra función utilizando el __doc__atributo.

Ahora, veamos las cadenas de documentos para la función incorporada print():

Ejemplo 3: Docstrings para la función print () incorporada

 print(print.__doc__)

Salida

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) Imprime los valores en una secuencia, o en sys.stdout por defecto. Argumentos de palabras clave opcionales: archivo: un objeto similar a un archivo (flujo); por defecto es el sys.stdout actual. sep: cadena insertada entre valores, por defecto un espacio. end: cadena añadida después del último valor, por defecto una nueva línea. flush: si se debe enjuagar el chorro a la fuerza.

Aquí, podemos ver que la documentación de la print()función está presente como __doc__atributo de esta función.

Cadenas de documentación de una sola línea en Python

Las cadenas de documentos de una sola línea son los documentos que caben en una línea.

Convenciones estándar para escribir cadenas de documentos de una sola línea:

  • Aunque son de una sola línea, seguimos usando las comillas triples alrededor de estas cadenas de documentos, ya que se pueden expandir fácilmente más adelante.
  • Las citas de cierre están en la misma línea que las de apertura.
  • No hay una línea en blanco ni antes ni después de la cadena de documentos.
  • No deben ser descriptivos, sino que deben seguir la estructura "Haga esto, devuelva eso" que termine con un punto.

Pongamos un ejemplo.

Ejemplo 4: escribir cadenas de documentos de una sola línea para una función

 def multiplier(a, b): """Takes in two numbers, returns their product.""" return a*b

Docstrings multilínea en Python

Las cadenas de documentos de varias líneas consisten en una línea de resumen como una cadena de documentos de una línea, seguida de una línea en blanco, seguida de una descripción más detallada.

El documento PEP 257 proporciona las convenciones estándar para escribir cadenas de documentos de varias líneas para varios objetos.

Algunos se enumeran a continuación:

1. Docstrings para módulos de Python

  • Las cadenas de documentación de los módulos de Python deben enumerar todas las clases, funciones, objetos y excepciones disponibles que se importan cuando se importa el módulo.
  • They should also have a one-line summary for each item.

They are written at the beginning of the Python file.

Let's look at the docstrings for the builtin module in Python called pickle.

Example 4: Docstrings of Python module

 import pickle print(pickle.__doc__)

Output

 Create portable serialized representations of Python objects. See module copyreg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object Misc variables: __version__ format_version compatible_formats

Here, we can see that the docstring written at the beginning of the pickle.py module file can be accessed as its docstring.

2. Docstrings for Python Functions

  • The docstring for a function or method should summarize its behavior and document its arguments and return values.
  • It should also list all the exceptions that can be raised and other optional arguments.

Example 5: Docstrings for Python functions

 def add_binary(a, b): ''' Returns the sum of two decimal numbers in binary digits. Parameters: a (int): A decimal integer b (int): Another decimal integer Returns: binary_sum (str): Binary string of the sum of a and b ''' binary_sum = bin(a+b)(2:) return binary_sum print(add_binary.__doc__)

Output

 Returns the sum of two decimal numbers in binary digits. Parameters: a (int): A decimal integer b (int): Another decimal integer Returns: binary_sum (str): Binary string of the sum of a and b

As you can see, we have included a short description of what the function does, the parameter it takes in and the value it returns. The string literal is embedded to the function add_binary as its __doc__ attribute.

3. Docstrings for Python Classes

  • The docstrings for classes should summarize its behavior and list the public methods and instance variables.
  • The subclasses, constructors, and methods should each have their own docstrings.

Example 6: Docstrings for Python class

Suppose we have a Person.py file with the following code:

 class Person: """ A class to represent a person.… Attributes ---------- name : str first name of the person surname : str family name of the person age : int age of the person Methods ------- info(additional=""): Prints the person's name and age. """ def __init__(self, name, surname, age): """ Constructs all the necessary attributes for the person object. Parameters ---------- name : str first name of the person surname : str family name of the person age : int age of the person """ self.name = name self.surname = surname self.age = age def info(self, additional=""): """ Prints the person's name and age. If the argument 'additional' is passed, then it is appended after the main info. Parameters ---------- additional : str, optional More info to be displayed (default is None) Returns ------- None """ print(f'My name is (self.name) (self.surname). I am (self.age) years old.' + additional)

Here, we can use the following code to access only the docstrings of the Person class:

 print(Person.__doc__)

Output

 A class to represent a person.… Attributes ---------- name : str first name of the person surname : str family name of the person age : int age of the person Methods ------- info(additional=""): Prints the person's name and age

Using the help() Function for Docstrings

We can also use the help() function to read the docstrings associated with various objects.

Example 7: Read Docstrings with the help() function

We can use the help() function on the class Person in Example 6 as:

 help(Person)

Output

 Help on class Person in module __main__: class Person(builtins.object) | Person(name, surname, age) | | A class to represent a person. | |… | | Attributes | ---------- | name : str | first name of the person | surname : str | family name of the person | age : int | age of the person | | Methods | ------- | info(additional=""): | Prints the person's name and age. | | Methods defined here: | | __init__(self, name, surname, age) | Constructs all the necessary attributes for the person object. | | Parameters | ---------- | name : str | first name of the person | surname : str | family name of the person | age : int | age of the person | | info(self, additional='') | Prints the person's name and age. | | If the argument 'additional' is passed, then it is appended after the main info. | | Parameters | ---------- | additional : str, optional | More info to be displayed (default is None) | | Returns | ------- | None | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)

Here, we can see that the help() function retrieves the docstrings of the Person class along with the methods associated with that class.

4. Docstrings for Python Scripts

  • The docstrings for Python script should document the script's functions and command-line syntax as a usable message.
  • It should serve as a quick reference to all the functions and arguments.

5. Docstrings for Python Packages

The docstrings for a Python package is written in the package's __init__.py file.

  • It should contain all the available modules and sub-packages exported by the package.

Docstring Formats

We can write docstring in many formats like the reStructured text (reST) format, Google format or the NumPy documentation format. To learn more, visit Popular Docstring Formats

También podemos generar documentación a partir de cadenas de documentos utilizando herramientas como Sphinx. Para obtener más información, visite la documentación oficial de Sphinx

Articulos interesantes...