Python Docstrings (z przykładami)

W tym samouczku dowiemy się o ciągach dokumentów Pythona. Dokładniej, na przykładach dowiemy się, jak i dlaczego używane są dokumenty.

Python docstrings to literały tekstowe, które pojawiają się zaraz po definicji funkcji, metody, klasy lub modułu. Weźmy przykład.

Przykład 1: ciągi dokumentów

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

Tutaj literał ciągu:

 '' 'Przyjmuje liczbę n, zwraca kwadrat n' ''

Wewnątrz potrójnych cudzysłowów jest docstring funkcji square(), gdyż pojawia się tuż po jej definicji.

Uwaga:""" do tworzenia ciągów dokumentów możemy również używać potrójnych cudzysłowów.

Komentarze w Pythonie a ciągi dokumentów

Komentarze w Pythonie

Komentarze to opisy, które pomagają programistom lepiej zrozumieć przeznaczenie i funkcjonalność programu. Są całkowicie ignorowane przez interpreter języka Python.

W Pythonie używamy symbolu skrótu #do pisania komentarza jednowierszowego. Na przykład,

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

Komentarze w Pythonie za pomocą ciągów

Jeśli nie przypiszemy ciągów do żadnej zmiennej, działają one jako komentarze. Na przykład,

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

Uwaga: w przypadku ciągów wieloliniowych używamy potrójnych cudzysłowów.

Python docstrings

Jak wspomniano powyżej, ciągi dokumentacyjne Pythona są ciągami używanymi bezpośrednio po definicji funkcji, metody, klasy lub modułu (jak w przykładzie 1 ). Służą do dokumentowania naszego kodu.

Możemy uzyskać dostęp do tych ciągów dokumentów za pomocą __doc__atrybutu.

Atrybut __doc__ w Pythonie

Ilekroć literały łańcuchowe występują tuż po definicji funkcji, modułu, klasy lub metody, są one skojarzone z obiektem jako ich __doc__atrybut. Możemy później użyć tego atrybutu, aby pobrać ten ciąg dokumentów.

Przykład 2: Drukowanie docstringu

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

Wynik

 Przyjmuje liczbę n, zwraca kwadrat n

Tutaj dokumentacja naszej square()funkcji jest dostępna za pomocą __doc__atrybutu.

Teraz spójrzmy na ciągi dokumentacyjne funkcji wbudowanej print():

Przykład 3: ciągi dokumentów dla wbudowanej funkcji print ()

 print(print.__doc__)

Wynik

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) Drukuje wartości domyślnie do strumienia lub do sys.stdout. Opcjonalne argumenty słów kluczowych: plik: obiekt plikopodobny (strumień); domyślnie bieżący sys.stdout. sep: ciąg wstawiany między wartościami, domyślnie spacja. koniec: ciąg dołączany po ostatniej wartości, domyślnie nowa linia. flush: czy wymusić spłukanie strumienia.

Tutaj widzimy, że dokumentacja print()funkcji jest obecna jako __doc__atrybut tej funkcji.

Jednowierszowe ciągi dokumentacyjne w Pythonie

Jednowierszowe dokumenty to dokumenty mieszczące się w jednej linii.

Standardowe konwencje pisania jednowierszowych dokumentów:

  • Mimo że są one jednowierszowe, nadal używamy potrójnych cudzysłowów wokół tych ciągów dokumentów, ponieważ można je później łatwo rozwinąć.
  • Kwotowania zamykające znajdują się w tym samym wierszu co kwotowania otwierające.
  • Nie ma pustej linii ani przed, ani po napisie.
  • Nie powinny być opisowe, a raczej muszą być zgodne ze strukturą „Zrób to, zwróć” zakończoną kropką.

Weźmy przykład.

Przykład 4: Napisz jednowierszowe ciągi dokumentacyjne dla funkcji

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

Wieloliniowe ciągi dokumentów w Pythonie

Wielowierszowe ciągi dokumentacyjne składają się z linii podsumowującej, podobnie jak jednowierszowe ciągi dokumentacyjne, po których następuje pusta linia, po której następuje bardziej rozbudowany opis.

Dokument PEP 257 zawiera standardowe konwencje pisania wielowierszowych ciągów dokumentów dla różnych obiektów.

Niektóre zostały wymienione poniżej:

1. Dokumenty dla modułów Pythona

  • Dokumentacja dotycząca modułów Pythona powinna zawierać listę wszystkich dostępnych klas, funkcji, obiektów i wyjątków, które są importowane podczas importowania modułu.
  • 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

Możemy również generować dokumentację z docstrów za pomocą narzędzi takich jak Sphinx. Aby dowiedzieć się więcej, odwiedź oficjalną dokumentację Sphinx

Interesujące artykuły...