Python Docstrings (con esempi)

In questo tutorial, impareremo a conoscere le docstring di Python. Più specificamente, impareremo come e perché le docstring vengono utilizzate con l'aiuto di esempi.

Le docstring Python sono le stringhe letterali che appaiono subito dopo la definizione di una funzione, un metodo, una classe o un modulo. Facciamo un esempio.

Esempio 1: Docstrings

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

Qui, la stringa letterale:

 '' 'Prende un numero n, restituisce il quadrato di n' ''

All'interno delle virgolette triple c'è la docstring della funzione square()come appare subito dopo la sua definizione.

Nota: possiamo anche utilizzare """virgolette triple per creare docstring.

Commenti Python vs Docstrings

Commenti Python

I commenti sono descrizioni che aiutano i programmatori a comprendere meglio l'intento e la funzionalità del programma. Sono completamente ignorati dall'interprete Python.

In Python, usiamo il simbolo hash #per scrivere un commento su una sola riga. Per esempio,

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

Commenti Python usando stringhe

Se non assegniamo stringhe a nessuna variabile, agiscono come commenti. Per esempio,

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

Nota: utilizziamo le virgolette triple per le stringhe su più righe.

Docstrings Python

Come accennato in precedenza, le docstring Python sono stringhe utilizzate subito dopo la definizione di una funzione, metodo, classe o modulo (come nell'esempio 1 ). Sono usati per documentare il nostro codice.

Possiamo accedere a queste docstring utilizzando l' __doc__attributo.

Attributo __doc__ di Python

Ogni volta che sono presenti stringhe letterali subito dopo la definizione di una funzione, modulo, classe o metodo, vengono associate all'oggetto come loro __doc__attributo. Successivamente possiamo utilizzare questo attributo per recuperare questa docstring.

Esempio 2: stampa di docstring

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

Produzione

 Prende un numero n, restituisce il quadrato di n

Qui, è square()possibile accedere alla documentazione della nostra funzione utilizzando l' __doc__attributo.

Ora, diamo un'occhiata alle docstring per la funzione incorporata print():

Esempio 3: Docstrings per la funzione built-in print ()

 print(print.__doc__)

Produzione

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) Stampa i valori su un flusso o su sys.stdout per impostazione predefinita. Argomenti delle parole chiave opzionali: file: un oggetto simile a un file (stream); il valore predefinito è l'attuale sys.stdout. sep: stringa inserita tra i valori, di default uno spazio. end: stringa aggiunta dopo l'ultimo valore, di default una nuova riga. flush: se scaricare forzatamente il flusso.

Qui, possiamo vedere che la documentazione della print()funzione è presente come __doc__attributo di questa funzione.

Docstring a riga singola in Python

Le docstring a riga singola sono i documenti che si adattano a una riga.

Convenzioni standard per scrivere docstring a riga singola:

  • Anche se sono a riga singola, utilizziamo ancora le virgolette triple attorno a queste docstring poiché possono essere espanse facilmente in seguito.
  • Le virgolette di chiusura sono sulla stessa riga delle virgolette di apertura.
  • Non c'è nessuna riga vuota né prima né dopo la docstring.
  • Non dovrebbero essere descrittivi, piuttosto devono seguire la struttura "Fai questo, restituisci quella" che termina con un punto.

Facciamo un esempio.

Esempio 4: scrivere docstrings su una sola riga per una funzione

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

Docstrings multilinea in Python

Le docstring su più righe consistono in una riga di riepilogo proprio come una docstring su una riga, seguita da una riga vuota, seguita da una descrizione più elaborata.

Il documento PEP 257 fornisce le convenzioni standard per scrivere docstring su più righe per vari oggetti.

Alcuni sono stati elencati di seguito:

1. Docstrings per moduli Python

  • Le docstring per i moduli Python dovrebbero elencare tutte le classi, funzioni, oggetti ed eccezioni disponibili che vengono importati quando il modulo viene importato.
  • 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

Possiamo anche generare documentazione da docstrings usando strumenti come Sphinx. Per saperne di più, visita la documentazione ufficiale della Sfinge

Articoli interessanti...