Python doc string style

Docstrings in Python

Python Docstring is the documentation string which is string literal, and it occurs in the class, module, function or method definition, and it is written as a first statement. Docstrings are accessible from the doc attribute for any of the Python object and also with the built-in help() function can come in handy.

One-line Docstrings

The one-line Docstrings are the Docstrings which fits all in one line. You can use one of the quotes, i.e., triple single or triple double quotes and opening quotes and closing quotes need to be the same. In the one-line Docstrings, closing quotes are in the same line as with the opening quotes. Also, the standard convention is to use the triple-double quotes.

def square(a):  '''Returns argument a is squared.'''  return a**a 
>>> print(square.__doc__) Returns argument a is squared. >>> help(square) Help on function square in module __main__:  square(a)  Returns argument a is squared. (END) 

Multi-line Docstrings

Multi-line Docstrings also contains the same string literals line as in One-line Docstrings, but it is followed by a single blank along with the descriptive text.

The general format for writing a Multi-line Docstring is as follows:

def some_function(argument1):  """Summary or Description of the Function   Parameters:  argument1 (int): Description of arg1   Returns:  int:Returning value   """   return argument1 

There are many Docstrings format available, but it is always better to use the formats which are easily recognized by the Docstring parser and also to fellow Data Scientist/programmers. There is no any rules and regulations for selecting a Docstring format, but the consistency of choosing the same format over the project is necessary. Also, It is preferred for you to use the formatting type which is mostly supported by Sphinx. The most common formats used are listed below.

Читайте также:  Titel
Formatting Type Description
NumPy/SciPy Combination of reStructured and GoogleDocstrings and supported by Sphinx
PyDoc Standard documentation module for Python and supported by Sphinx
EpyDoc Render Epytext as series of HTML documents and a tool for generating API documentation for Python modules based on their Docstrings
Google Docstrings Google’s Style

Google Style

Google Style is easier and more intuitive to use. It can be used for the shorter form of documentation.

class Vehicles(object):  '''  The Vehicle object contains a lot of vehicles   Args:  arg (str): The arg is used for.  *args: The variable arguments are used for.  **kwargs: The keyword arguments are used for.   Attributes:  arg (str): This is where we store arg,  '''  def __init__(self, arg, *args, **kwargs):  self.arg = arg   def cars(self, distance,destination):  '''We can't travel distance in vehicles without fuels, so here is the fuels   Args:  distance (int): The amount of distance traveled  destination (bool): Should the fuels refilled to cover the distance?   Raises:  RuntimeError: Out of fuel   Returns:  cars: A car mileage  '''  pass 

The Google Style is better than Sphinx style. It also has an inconvenient feature, i.e. In the above code, the multi-line description of the distance would look messy. That is why the Numpy can be used for the more extended form of documentation.

Numpy Style

Numpy style has a lot of details in the documentation. It is more verbose than other documentation, but it is an excellent choice if you want to do detailed documentation, i.e., extensive documentation of all the functions and parameters.

class Vehicles(object):  '''  The Vehicles object contains lots of vehicles   Parameters  ----------  arg : str  The arg is used for .  *args  The variable arguments are used for .  **kwargs  The keyword arguments are used for .   Attributes  ----------  arg : str  This is where we store arg,  '''  def __init__(self, arg, *args, **kwargs):  self.arg = arg   def cars(self, distance, destination):  '''We can't travel distance in vehicles without fuels, so here is the fuels   Parameters  ----------  distance : int  The amount of distance traveled  destination : bool  Should the fuels refilled to cover the distance?   Raises  ------  RuntimeError  Out of fuel   Returns  -------  cars  A car mileage  '''  pass 

The above example is more verbose than any other documentation. It is more lengthy and could only be used for the long and detailed documentation.

Python Built-in Docstrings

You can also view the built-in Python Docstrings.

The all the built-in function, classes, methods have the actual human description attached to it. You can access it in one of two ways.

import time print(time.__doc__) 

Similarly, the help can be used by:

help(print)  Help on built-in function print in module builtins:  print(. )  print(value, . , sep=' ', end='\n', file=sys.stdout, flush=False)   Prints the values to a stream, or to sys.stdout by default.  Optional keyword arguments:  file: a file-like object (stream); defaults to the current sys.stdout.  sep: string inserted between values, default a space.  end: string appended after the last value, default a newline.  flush: whether to forcibly flush the stream. 

Python PEP8

PEP 8, sometimes spelled PEP8 or PEP-8, is a document that provides guidelines and best practices on how to write Python code. It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The primary focus of PEP 8 is to improve the readability and consistency of Python code. You can learn about these by reading the full PEP 8 documentation

Naming Styles

The table below outlines some of the common naming styles in Python code and when you should use them:

Type Naming Convention Examples
Functions Use a lowercase word or words. Separate words by underscores to improve readability. function, my_function
Variable Use a lowercase single letter, word, or words. Separate words with underscores to improve readability. x, var, my_variable
Class Start each word with a capital letter. Do not separate words with underscores. This style is called camel case. Model, MyClass
Method Use a lowercase word or words. Separate words with underscores to improve readability. class_method, method
Constant Use an uppercase single letter, word, or words. Separate words with underscores to improve readability. CONSTANT, MY_CONSTANT, MY_LONG_CONSTANT
Module Use a short, lowercase word or words. Separate words with underscores to improve readability. module.py, my_module.py
Package Use a short, lowercase word or words. Do not separate words with underscores. package, mypackage

Recommendations

  • Avoid trailing whitespace anywhere. Because it’s usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don’t preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.
  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, , !=, <>, =, in, not in, is, is not), Booleans (and, or, not).
  • If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.
i = i + 1 submitted += 1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b) 
i=i+1 submitted +=1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) 
  • Don’t use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter.
def complex(real, imag=0.0):  return magic(r=real, i=imag) 
def complex(real, imag = 0.0):  return magic(r = real, i = imag) 

When combining an argument annotation with a default value, however, do use spaces around the = sign:

def munge(sep: AnyStr = None): . def munge(input: AnyStr, sep: AnyStr = None, limit=1000): . 
def munge(input: AnyStr=None): . def munge(input: AnyStr, limit = 1000): . 

Источник

Docstring в Python: использование и стандарты документирования

Docstring в Python: использование и стандарты документирования

Docstring, или строка документации — это инструмент в Python, который используется для документирования определенных сегментов кода. Обычно docstring помещается сразу после определения функции, метода, класса или модуля.

Docstring оформляется в виде строкового литерала и может быть как однострочным, так и многострочным.

Создание Docstring

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

def add_numbers(x, y): """Adds two numbers together.""" return x + y

Этот docstring описывает, что делает функция add_numbers() .

Docstring также может быть многострочным, что особенно полезно для более сложных функций или методов:

def complex_function(x, y, z): """ This is a complex function that takes three parameters and does many things. """ # function body

Использование Docstring

Docstring можно просмотреть с помощью функции help() , которая возвращает информацию о том, как использовать функцию, класс, метод или модуль.

Исполнив эту команду, вы увидите вывод справочной информации, включая docstring:

Help on function add_numbers in module __main__: add_numbers(x, y) Adds two numbers together.

Docstring также можно получить с помощью атрибута __doc__ .

Стандарты оформления Docstring

Есть несколько широко распространенных стандартов оформления docstring, таких как Google, NumPy и reStructuredText (reST). Каждый из них имеет свои собственные соглашения о том, как структурировать и форматировать docstring.

Например, в стиле Google выглядит так:

def sample_function(arg1, arg2): """ Summary line. Extended description of function. Args: arg1 (int): Description of arg1 arg2 (str): Description of arg2 Returns: bool: Description of return value """ return True

Расширенное использование Docstring

Помимо базового использования в функциях и методах, Docstring также применим к классам и модулям.

Docstring классов

Когда Docstring применяется к классу, он должен содержать краткое описание того, что делает класс, а также его атрибуты и методы.

class MyClass: """ This is an example class. Attributes: attr1: A string representing the attribute. Methods: method1: Prints the attribute. """ attr1 = "This is an attribute" def method1(self): """Prints the attribute.""" print(self.attr1)

Docstring модулей

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

""" This is an example module. This module demonstrates the usage of docstrings in Python. """ # Module code

Автогенерация документации

Один из наиболее важных аспектов использования Docstring — возможность автоматической генерации документации. Инструменты, такие как Sphinx, могут считывать ваш Docstring и автоматически создавать документацию в форматах HTML, PDF и других.

Заключение

Docstring является важным инструментом в Python, который используется для документирования вашего кода. Он описывает, что делает ваша функция, метод, класс или модуль, что помогает другим разработчикам понять ваш код. Важно следовать определенным стандартам оформления docstring, чтобы обеспечить последовательность и четкость вашей документации.

Методы и способы поиска элемента в списке в Python

Методы и способы поиска элемента в списке в Python

Как работает метод update() в словарях: синтаксис и примеры

Как работает метод update() в словарях: синтаксис и примеры

Функция reduce() модуля functools в Python: синтаксис и примеры использования

Функция reduce() модуля functools в Python: синтаксис и примеры использования

Глобальные переменные и global в Python

Глобальные переменные и global в Python

Извлечение случайного элемента из списка в Python

Извлечение случайного элемента из списка в Python

Основные способы конвертации кортежа в список в Python

Основные способы конвертации кортежа в список в Python

Источник

Оцените статью