Python docstrings (s primjerima)

U ovom uputstvu naučit ćemo o Python dokumentima. Točnije, naučit ćemo kako i zašto se docstrings koriste uz pomoć primjera.

Python docstrings su literalni nizovi koji se pojavljuju odmah nakon definicije funkcije, metode, klase ili modula. Uzmimo primjer.

Primjer 1: docstrings

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

Evo doslovnog niza:

 '' 'Uzima broj n, vraća kvadrat od n' ''

Unutar trostrukih navodnika nalazi se docstring funkcije square()koja se pojavljuje odmah nakon njezine definicije.

Napomena: Također možemo koristiti trostruke """citate za stvaranje docstringsa.

Python komentari u odnosu na docstrings

Python komentari

Komentari su opisi koji pomažu programerima da bolje razumiju namjeru i funkcionalnost programa. U potpunosti ih ignorira Python tumač.

U Pythonu koristimo simbol hash #za pisanje komentara u jednom retku. Na primjer,

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

Python komentira koristeći stringove

Ako niti jednoj varijabli ne dodijelimo nizove, oni će djelovati kao komentari. Na primjer,

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

Napomena: Za višeredne nizove koristimo trostruke navodnike.

Python docstrings

Kao što je gore spomenuto, Python docstrings su nizovi koji se koriste odmah nakon definicije funkcije, metode, klase ili modula (kao u Primjeru 1 ). Koriste se za dokumentiranje našeg koda.

Tim dokumentima možemo pristupiti pomoću __doc__atributa.

Python __doc__ atribut

Kad god su string literali prisutni neposredno nakon definicije funkcije, modula, klase ili metode, oni su povezani s objektom kao njihovim __doc__atributom. Kasnije možemo koristiti ovaj atribut za dohvaćanje ove docstringa.

Primjer 2: Ispis docstringa

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

Izlaz

 Uzima broj n, vraća kvadrat od n

Ovdje se dokumentaciji naše square()funkcije može pristupiti pomoću __doc__atributa.

Sada, pogledajmo docstrings za ugrađenu funkciju print():

Primjer 3: Docstrings za ugrađenu funkciju print ()

 print(print.__doc__)

Izlaz

ispis (vrijednost,…, sep = '', end = ' n', datoteka = sys.stdout, flush = False) Ispisuje vrijednosti u tok ili prema zadanim postavkama u sys.stdout. Izborni argumenti ključne riječi: datoteka: objekt sličan datoteci (tok); zadani je trenutni sys.stdout. sep: niz umetnut između vrijednosti, zadani razmak. kraj: niz dodan nakon posljednje vrijednosti, zadani novi redak. ispiranje: da li prisilno isprati potok.

Ovdje možemo vidjeti da je dokumentacija print()funkcije prisutna kao __doc__atribut ove funkcije.

Jednoredni docstrings u Pythonu

Jednoredni dokumenti su dokumenti koji stanu u jedan redak.

Standardne konvencije za pisanje jednorednih docstrings:

  • Iako su jednoslojni, još uvijek koristimo trostruke citate oko ovih docstrings jer ih kasnije možete lako proširiti.
  • Završne kotacije nalaze se u istoj liniji kao i početne kotacije.
  • Nema praznog retka ni prije ni poslije docstringa.
  • Ne bi trebali biti opisni, već moraju slijediti strukturu "Učini to, vrati ono" koja završava točkom.

Uzmimo primjer.

Primjer 4: Napišite funkciju docstrringa u jednom retku

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

Višeredni docstrings u Pythonu

Nizovi dokumenata s više redaka sastoje se od sažetka, baš kao i kod redaka u jednom retku, nakon čega slijedi prazan redak, nakon čega slijedi detaljniji opis.

Dokument PEP 257 pruža standardne konvencije za pisanje višerednih dokumenata za različite objekte.

Neki su navedeni u nastavku:

1. Docstrings za Python module

  • Docstrings za Python module trebali bi navesti sve dostupne klase, funkcije, objekte i iznimke koje se uvoze prilikom uvoza modula.
  • 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

Također možemo generirati dokumentaciju iz docstrings koristeći alate poput Sphinx. Da biste saznali više, posjetite službenu dokumentaciju o sfingi

Zanimljivi članci...