Docstrings Python (avec exemples)

Dans ce didacticiel, nous allons en apprendre davantage sur les docstrings Python. Plus précisément, nous apprendrons comment et pourquoi les docstrings sont utilisés à l'aide d'exemples.

Les docstrings Python sont les littéraux de chaîne qui apparaissent juste après la définition d'une fonction, d'une méthode, d'une classe ou d'un module. Prenons un exemple.

Exemple 1: Docstrings

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

Ici, la chaîne littérale:

 '' 'Prend un nombre n, renvoie le carré de n' ''

À l'intérieur des guillemets triples se trouve la docstring de la fonction square()telle qu'elle apparaît juste après sa définition.

Remarque: nous pouvons également utiliser des """guillemets triples pour créer des docstrings.

Commentaires Python vs Docstrings

Commentaires Python

Les commentaires sont des descriptions qui aident les programmeurs à mieux comprendre l'intention et la fonctionnalité du programme. Ils sont complètement ignorés par l'interpréteur Python.

En Python, nous utilisons le symbole de hachage #pour écrire un commentaire sur une seule ligne. Par exemple,

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

Commentaires Python utilisant des chaînes

Si nous n'affectons de chaînes à aucune variable, elles agissent comme des commentaires. Par exemple,

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

Remarque: nous utilisons des guillemets triples pour les chaînes multilignes.

Docstrings Python

Comme mentionné ci-dessus, les docstrings Python sont des chaînes utilisées juste après la définition d'une fonction, d'une méthode, d'une classe ou d'un module (comme dans l' exemple 1 ). Ils sont utilisés pour documenter notre code.

Nous pouvons accéder à ces docstrings en utilisant l' __doc__attribut.

Attribut Python __doc__

Chaque fois que des littéraux de chaîne sont présents juste après la définition d'une fonction, d'un module, d'une classe ou d'une méthode, ils sont associés à l'objet en tant __doc__qu'attribut. Nous pouvons plus tard utiliser cet attribut pour récupérer cette docstring.

Exemple 2: impression de docstring

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

Production

 Prend un nombre n, renvoie le carré de n

Ici, la documentation de notre square()fonction est accessible à l'aide de l' __doc__attribut.

Maintenant, regardons les docstrings pour la fonction intégrée print():

Exemple 3: Docstrings pour la fonction intégrée print ()

 print(print.__doc__)

Production

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) Imprime les valeurs dans un flux ou dans sys.stdout par défaut. Arguments de mots clés facultatifs: fichier: un objet semblable à un fichier (flux); par défaut, le sys.stdout actuel. sep: chaîne insérée entre les valeurs, par défaut un espace. end: chaîne ajoutée après la dernière valeur, par défaut une nouvelle ligne. flush: s'il faut forcer le vidage du flux.

Ici, nous pouvons voir que la documentation de la print()fonction est présente comme __doc__attribut de cette fonction.

Docstrings sur une seule ligne en Python

Les docstrings à une seule ligne sont les documents qui tiennent sur une seule ligne.

Conventions standard pour écrire des docstrings sur une seule ligne:

  • Même s'ils sont sur une seule ligne, nous utilisons toujours les guillemets triples autour de ces docstrings car ils peuvent être développés facilement plus tard.
  • Les guillemets de clôture sont sur la même ligne que les guillemets d'ouverture.
  • Il n'y a pas de ligne vide avant ou après la docstring.
  • Ils ne doivent pas être descriptifs, mais doivent suivre la structure «Faites ceci, retournez cela» se terminant par un point.

Prenons un exemple.

Exemple 4: Ecrire des docstrings sur une seule ligne pour une fonction

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

Docstrings multilignes en Python

Les docstrings multilignes se composent d'une ligne de résumé comme une docstring d'une ligne, suivie d'une ligne vide, suivie d'une description plus élaborée.

Le document PEP 257 fournit les conventions standard pour écrire des docstrings multilignes pour divers objets.

Certains ont été répertoriés ci-dessous:

1. Docstrings pour les modules Python

  • Les docstrings pour les modules Python doivent répertorier toutes les classes, fonctions, objets et exceptions disponibles qui sont importés lorsque le module est importé.
  • 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

Nous pouvons également générer de la documentation à partir de docstrings en utilisant des outils comme Sphinx. Pour en savoir plus, visitez la documentation officielle du Sphinx

Articles intéressants...