Комментарии (1)
Ответ сгенерирован нейросетью и может содержать ошибки
Форматы написания docstring в Python
Docstring — это документационная строка, описывающая модули, функции, классы и методы. В Python существует несколько стандартных форматов для их написания. Каждый имеет свои преимущества и используется в разных проектах.
1. Google Style (Google docstring)
Один из самых популярных и читаемых форматов. Широко используется в Google, YouTube и других проектах.
def calculate_sum(a: int, b: int) -> int:
"""Calculates the sum of two numbers.
This function takes two integers and returns their sum.
Args:
a: The first number to add.
b: The second number to add.
Returns:
The sum of a and b.
Raises:
TypeError: If a or b is not an integer.
Examples:
>>> calculate_sum(2, 3)
5
>>> calculate_sum(-1, 1)
0
"""
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("Both arguments must be integers")
return a + b
class DataProcessor:
"""Processes and validates data from various sources.
This class provides methods for cleaning, transforming, and
validating data with support for multiple data formats.
Attributes:
source_type: The type of data source (csv, json, xml).
strict_mode: Whether to raise errors on invalid data.
"""
def __init__(self, source_type: str, strict_mode: bool = False):
"""Initialize the DataProcessor.
Args:
source_type: Type of data source (csv, json, xml).
strict_mode: If True, raise exceptions on invalid data.
"""
self.source_type = source_type
self.strict_mode = strict_mode
2. NumPy Style (NumPy docstring)
Традиционный формат, используемый в NumPy, SciPy и научных проектах. Более детальный и подробный.
def matrix_multiply(a, b):
"""
Multiply two matrices.
Parameters
----------
a : ndarray
First matrix of shape (m, n).
b : ndarray
Second matrix of shape (n, p).
Returns
-------
ndarray
Product matrix of shape (m, p).
Raises
------
ValueError
If the matrices have incompatible dimensions for multiplication.
Notes
-----
The algorithm uses standard matrix multiplication.
Time complexity is O(n^3).
See Also
--------
numpy.dot : Dot product
numpy.matmul : Matrix multiplication
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6], [7, 8]])
>>> matrix_multiply(a, b)
array([[19, 22],
[43, 50]])
"""
pass
3. Sphinx/reStructuredText Style
Визуальный стиль, используемый в Sphinx для генерации документации. Часто встречается в официальной документации Python.
def parse_config(filepath):
"""
Parse configuration file.
:param filepath: Path to configuration file
:type filepath: str
:returns: Parsed configuration dictionary
:rtype: dict
:raises FileNotFoundError: If configuration file does not exist
:raises ValueError: If configuration format is invalid
:Example:
>>> config = parse_config(/etc/app.conf)
>>> config[debug]
True
.. note::
Configuration files must be in YAML format.
.. warning::
Never commit config files with secrets to version control!
"""
pass
class DatabaseConnection:
"""
Manages connection to PostgreSQL database.
:ivar host: Database host
:vartype host: str
:ivar port: Database port
:vartype port: int
"""
def execute_query(self, query, params=None):
"""
Execute SQL query.
:param query: SQL query string
:type query: str
:param params: Query parameters
:type params: dict or None
:returns: Query result
:rtype: list
"""
pass
4. PEP 257 Style (Simple/Plain style)
Минималистичный стиль, рекомендованный PEP 257. Простой и лаконичный.
def factorial(n):
"""Return the factorial of n.
Factorial is calculated as n * (n-1) * (n-2) * ... * 1.
Args:
n: A non-negative integer.
Returns:
The factorial of n as an integer.
"""
if n < 0:
raise ValueError("n must be non-negative")
return 1 if n == 0 else n * factorial(n - 1)
5. Epydoc Style
Формат для инструмента Epydoc, ориентированный на генерацию HTML документации.
def encrypt_password(password):
"""
Encrypt password using bcrypt algorithm.
@param password: Plain text password to encrypt
@type password: str
@return: Encrypted password hash
@rtype: str
@raise ValueError: If password is empty or None
@author: Security Team
@version: 1.0
@since: 2.1.0
@example:
>>> encrypted = encrypt_password("mypassword")
>>> len(encrypted) == 60
True
"""
pass
6. YAPF/Black Compatible (Modern Style)
Современный стиль, совместимый с форматерами кода.
def process_data(data: list[dict], filter_key: str = None) -> list[dict]:
"""Process and filter data.
Args:
data: List of dictionaries to process.
filter_key: Optional key to filter data by.
Returns:
Processed data as list of dictionaries.
"""
pass
Сравнение форматов
| Формат | Популярность | Читаемость | Интеграция | Используется в |
|---|---|---|---|---|
| Очень высокая | ✅ Отличная | Sphinx, IDE | Google, FastAPI | |
| NumPy | Высокая | ✅ Хорошая | Sphinx | NumPy, SciPy, Pandas |
| Sphinx | Высокая | ✅ Хорошая | Sphinx | Python docs |
| PEP 257 | Высокая | ✅ Простая | Стандарт | Стандартная библиотека |
| Epydoc | Средняя | ⚠️ Сложная | Epydoc | Старые проекты |
Best Practices
- Выбери один стиль и придерживайся его на протяжении всего проекта
- Используй type hints вместе с docstrings для лучшей типизации
- Документируй исключения — какие ошибки может выбросить функция
- Приводи примеры использования в Examples разделе
- Обновляй docstrings вместе с кодом
- Используй инструменты вроде
pdoc,Sphinxилиpydocдля генерации документации
Мой личный рекомендуемый выбор — Google Style, так как он обладает оптимальным балансом между читаемостью и детализацией.