Python Docstrings (com exemplos)

Neste tutorial, aprenderemos sobre docstrings do Python. Mais especificamente, aprenderemos como e por que docstrings são usados ​​com a ajuda de exemplos.

As docstrings do Python são as strings literais que aparecem logo após a definição de uma função, método, classe ou módulo. Vamos dar um exemplo.

Exemplo 1: Docstrings

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

Aqui, a string literal:

 '' 'Obtém um número n, retorna o quadrado de n' ''

Dentro das aspas triplas está o docstring da função square()como aparece logo após sua definição.

Nota: Também podemos usar """citações triplas para criar docstrings.

Comentários Python vs Docstrings

Comentários Python

Os comentários são descrições que ajudam os programadores a entender melhor a intenção e a funcionalidade do programa. Eles são completamente ignorados pelo interpretador Python.

Em Python, usamos o símbolo hash #para escrever um comentário de uma única linha. Por exemplo,

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

Comentários Python usando strings

Se não atribuirmos strings a nenhuma variável, elas atuam como comentários. Por exemplo,

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

Observação: usamos aspas triplas para strings de várias linhas.

Docstrings Python

Como mencionado acima, docstrings Python são strings usadas logo após a definição de uma função, método, classe ou módulo (como no Exemplo 1 ). Eles são usados ​​para documentar nosso código.

Podemos acessar essas docstrings usando o __doc__atributo.

Atributo Python __doc__

Sempre que literais de string estão presentes logo após a definição de uma função, módulo, classe ou método, eles são associados ao objeto como seu __doc__atributo. Posteriormente, podemos usar este atributo para recuperar esta docstring.

Exemplo 2: Impressão de docstring

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

Resultado

 Pega um número n, retorna o quadrado de n

Aqui, a documentação de nossa square()função pode ser acessada usando o __doc__atributo.

Agora, vamos dar uma olhada em docstrings para a função integrada print():

Exemplo 3: Docstrings para a função embutida print ()

 print(print.__doc__)

Resultado

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) Imprime os valores em um fluxo ou em sys.stdout por padrão. Argumentos de palavra-chave opcionais: arquivo: um objeto semelhante a um arquivo (fluxo); o padrão é o sys.stdout atual. sep: string inserida entre valores, um espaço padrão. end: string anexada após o último valor, padrão uma nova linha. flush: se deve forçar a descarga do fluxo.

Aqui, podemos ver que a documentação da print()função está presente como o __doc__atributo desta função.

Docstrings de linha única em Python

Docstrings de linha única são os documentos que cabem em uma linha.

Convenções padrão para escrever docstrings de linha única:

  • Mesmo que sejam de uma linha, ainda usamos aspas triplas em torno dessas docstrings, pois podem ser facilmente expandidas mais tarde.
  • The closing quotes are on the same line as the opening quotes.
  • There's no blank line either before or after the docstring.
  • They should not be descriptive, rather they must follow "Do this, return that" structure ending with a period.

Let's take an example.

Example 4: Write single-line docstrings for a function

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

Multi-line Docstrings in Python

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 PEP 257 document provides the standard conventions to write multi-line docstrings for various objects.

Some have been listed below:

1. Docstrings for Python Modules

  • The docstrings for Python Modules should list all the available classes, functions, objects and exceptions that are imported when the module is imported.
  • 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

Também podemos gerar documentação a partir de docstrings usando ferramentas como o Sphinx. Para saber mais, visite a documentação oficial do Sphinx

Artigos interessantes...