Python Docstrings (cu exemple)

În acest tutorial, vom învăța despre șirurile de documente Python. Mai precis, vom afla cum și de ce sunt folosite șirurile de documente cu ajutorul exemplelor.

Șirurile de documente Python sunt literele șirului care apar imediat după definirea unei funcții, metode, clase sau module. Să luăm un exemplu.

Exemplul 1: Docstrings

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

Aici, literalul șirului:

 '' 'Introduce un număr n, returnează pătratul lui n' ''

În interiorul ghilimelelor triple se află șirul de documente al funcției square()așa cum apare imediat după definirea ei.

Notă: Putem folosi și """citate triple pentru a crea docstrings.

Python Comments vs Docstrings

Comentarii Python

Comentariile sunt descrieri care îi ajută pe programatori să înțeleagă mai bine intenția și funcționalitatea programului. Acestea sunt complet ignorate de interpretul Python.

În Python, folosim simbolul hash #pentru a scrie un comentariu pe o singură linie. De exemplu,

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

Comentarii Python folosind șiruri

Dacă nu atribuim șiruri niciunei variabile, acestea acționează ca comentarii. De exemplu,

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

Notă: Folosim ghilimele triple pentru șirurile cu mai multe linii.

Șiruri de documente Python

Așa cum am menționat mai sus, șirurile de documente Python sunt șiruri utilizate imediat după definirea unei funcții, metode, clase sau module (ca în Exemplul 1 ). Sunt folosite pentru a documenta codul nostru.

Putem accesa aceste docstrings folosind __doc__atributul.

Atributul Python __doc__

Ori de câte ori literele șirului sunt prezente imediat după definirea unei funcții, module, clase sau metode, acestea sunt asociate cu obiectul ca __doc__atribut al acestora . Putem utiliza ulterior acest atribut pentru a prelua acest șir de documente.

Exemplul 2: Imprimarea șirului de documente

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

Ieșire

 Ia un număr n, returnează pătratul lui n

Aici, documentația square()funcției noastre poate fi accesată folosind __doc__atributul.

Acum, să ne uităm la docstrings pentru funcția încorporată print():

Exemplul 3: Docstrings pentru funcția print () încorporată

 print(print.__doc__)

Ieșire

print (valoare, …, sep = '', end = ' n', file = sys.stdout, flush = False) Tipărește valorile într-un flux sau în sys.stdout în mod implicit. Argumente opționale ale cuvintelor cheie: fișier: un obiect asemănător unui fișier (flux); implicit la sys.stdout curent. sep: șir inserat între valori, implicit un spațiu. end: șir adăugat după ultima valoare, implicit o linie nouă. flush: dacă se spală forțat cursul.

Aici, putem vedea că documentația print()funcției este prezentă ca __doc__atribut al acestei funcții.

Docstrings cu o singură linie în Python

Șirurile de documente cu o singură linie sunt documentele care se încadrează într-o singură linie.

Convenții standard pentru a scrie docstrings pe o singură linie:

  • Chiar dacă sunt cu o singură linie, folosim în continuare ghilimelele triple în jurul acestor șiruri de documente, deoarece acestea pot fi extinse cu ușurință ulterior.
  • Ghilimelele de închidere sunt pe aceeași linie cu ghilimelele de deschidere.
  • Nu există nicio linie goală nici înainte, nici după șirul de documente.
  • Ele nu trebuie să fie descriptive, ci mai degrabă trebuie să urmeze structura „Fă acest lucru, returnează acel” care se termină cu un punct.

Să luăm un exemplu.

Exemplul 4: Scrieți șiruri de documente cu o singură linie pentru o funcție

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

Docstrings multi-linie în Python

Șirurile de documente cu mai multe linii constau dintr-o linie de rezumat la fel ca o șir de documente pe o singură linie, urmată de o linie goală, urmată de o descriere mai elaborată.

Documentul PEP 257 oferă convențiile standard pentru a scrie docstringuri cu mai multe linii pentru diferite obiecte.

Unele au fost enumerate mai jos:

1. Docstrings pentru module Python

  • Șirurile de documente pentru modulele Python ar trebui să listeze toate clasele, funcțiile, obiectele și excepțiile disponibile care sunt importate atunci când modulul este importat.
  • 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

De asemenea, putem genera documentație din docstrings folosind instrumente precum Sphinx. Pentru a afla mai multe, vizitați Documentația oficială Sfinx

Articole interesante...