Строки документации Python (с примерами)

В этом руководстве мы узнаем о строках документации Python. Более конкретно, мы узнаем, как и почему используются строки документации, с помощью примеров.

Строки документации Python - это строковые литералы, которые появляются сразу после определения функции, метода, класса или модуля. Возьмем пример.

Пример 1: строки документации

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

Здесь строковый литерал:

 '' 'Принимает число n, возвращает квадрат n' ''

Внутри тройных кавычек находится строка документации функции, square()которая появляется сразу после ее определения.

Примечание. Мы также можем использовать тройные """кавычки для создания строк документации.

Комментарии Python против строк документации

Комментарии Python

Комментарии - это описания, которые помогают программистам лучше понять назначение и функциональность программы. Интерпретатор Python полностью игнорирует их.

В Python мы используем символ решетки #для написания однострочного комментария. Например,

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

Комментарии Python с использованием строк

Если мы не присваиваем строки какой-либо переменной, они действуют как комментарии. Например,

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

Примечание. Для многострочных строк мы используем тройные кавычки.

Строки документации Python

Как упоминалось выше, строки документации Python - это строки, используемые сразу после определения функции, метода, класса или модуля (как в примере 1 ). Они используются для документирования нашего кода.

Мы можем получить доступ к этим строкам документации с помощью __doc__атрибута.

Атрибут Python __doc__

Всякий раз, когда строковые литералы присутствуют сразу после определения функции, модуля, класса или метода, они связаны с объектом в качестве своего __doc__атрибута. Позже мы можем использовать этот атрибут для получения этой строки документации.

Пример 2: Печать строки документации

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

Вывод

 Принимает число n, возвращает квадрат n.

Здесь к документации по нашей square()функции можно получить доступ с помощью __doc__атрибута.

Теперь давайте посмотрим на строки документации для встроенной функции print():

Пример 3: строки документации для встроенной функции print ()

 print(print.__doc__)

Вывод

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) Печатает значения в поток или в sys.stdout по умолчанию. Необязательные аргументы ключевого слова: file: файловый объект (поток); по умолчанию используется текущий sys.stdout. sep: строка, вставленная между значениями, по умолчанию - пробел. конец: строка, добавляемая после последнего значения, по умолчанию - новая строка. flush: нужно ли принудительно смывать поток.

Здесь мы видим, что документация print()функции присутствует как __doc__атрибут этой функции.

Однострочные строки документации в Python

Строки однострочных документов - это документы, которые помещаются в одну строку.

Стандартные соглашения о написании однострочных строк документации:

  • Несмотря на то, что они однострочные, мы по-прежнему используем тройные кавычки вокруг этих строк документации, так как они могут быть легко расширены позже.
  • Котировки закрытия находятся на той же строке, что и котировки открытия.
  • Ни перед, ни после строки документации нет пустой строки.
  • Они не должны быть описательными, они должны следовать структуре «Сделай это, верни то», оканчиваясь точкой.

Возьмем пример.

Пример 4: напишите однострочную документацию для функции

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

Многострочные строки документации в Python

Многострочные строки документации состоят из итоговой строки, как и однострочной строки документации, за которой следует пустая строка, за которой следует более подробное описание.

Документ PEP 257 предоставляет стандартные соглашения о написании многострочных строк документации для различных объектов.

Некоторые из них перечислены ниже:

1. Строки документации для модулей Python

  • В строках документации для модулей Python должны быть перечислены все доступные классы, функции, объекты и исключения, которые импортируются при импорте модуля.
  • 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

Мы также можем создавать документацию из строк документации, используя такие инструменты, как Sphinx. Чтобы узнать больше, посетите официальную документацию Sphinx.

Интересные статьи...