Docstring

Содержание
Введение
Пример написания
help: чтение
Похожие статьи

Введение

В программировании строка документа - это строковый литерал, указанный в исходном коде, который используется, как и комментарий, для документирования определенного сегмента кода.

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

Это позволяет программисту проверять эти комментарии во время выполнения, например, в виде интерактивной справочной системы или в виде метаданных.

По-видимому, он был впервые представлен в оригинальной реализации Emacs TECO.

Языки, поддерживающие docstrings, включают Python (см. PEP 257 ) , Lisp, Elixir, Clojure, Gherkin, Julia и Haskell.

Примеры

В начале можно описать что делает функция, затем перечислить параметры и возвращаемое значение.

Например, PyCharm предлагает использовать термин param то есть параметры и я считаю, что это правильно.

def sum(first: float, second: float) -> float: """ Adds two float values :param first: :param second: :return: first + second """ return(first + second)

Некоторые авторы, например, на Pluralsight используют термин Args то есть аргументы я считаю это некорректным.

"""Retrieve and print words from a URL. Usage: python3 words.py <URL> """ import sys from urllib.request import urlopen def fetch_words(url): """Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document """ # PEP 257 # story = urlopen("http://sixty-north.com/c/t.txt") story = urlopen(url) story_words = [] for line in story: line_words = line.decode("utf8").split() for word in line_words: story_words.append(word) story.close() return story_words def print_items(story_words): """Print items one per line. Args: An iterable series of printable items. """ for word in story_words: print(word) def main(url): words = fetch_words(url) print_items(words) if __name__ == "__main__": main(sys.argv[1])

Созданный нами docstring будет хорошо выглядеть в выводе help()

Изучение help

➭ python

Python 3.9.5 (default, Jun 15 2021, 15:30:04) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information.

>>> import words
>>> help(words)

Help on module words: NAME words - Retrieve and print words from a URL. DESCRIPTION Usage: python3 words.py <URL> FUNCTIONS fetch_words(url) Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document main(url) print_items(story_words) Print items one per line. Args: An iterable series of printable items. FILE /home/andrei/python/words.py

Article author: Andrei Olegovich

Похожие статьи
Основы Python
configparser
docstring
#!: Shebang
Объекты
Итерация
os
pathlib

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: