Mochinov

Untitled

May 10th, 2024
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.43 KB | None | 0 0
  1.  
  2. ---
  3. ## 📝 Docstring
  4.  
  5. Одна из важных вещей в любом коде – **читабельность**.
  6. Однако не всегда получается оптимизировать алгоритмы или названия переменных, функций,
  7. методов или классов для полного понимания кода. Для этого нам нужны docstring. <br>
  8. Docstring пишется только для объемных и сложных задач
  9. (наличие множества переменных, длинной цепочки построения логики и т.д.). <br><br>
  10. <b>Обновление 04.04.2024:</b> docstring пишутся по правилам google. https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html <br><br>
  11. В самих docstring описываются как минимум 4 вещи:
  12. 1. основная идея функции, метода или класса;
  13. 2. род используемых переменных (Опционально, если не указана аннотация);
  14. 3. исключения (Если добавлено больше чем одно исключение или исключение является кастомное);
  15. 4. ожидаемый результат, то есть то, что мы получаем на выходе (этой частью можно пренебрегать,
  16. если указан ожидаемый тип ответа после аргументов; например, def sum(a, b) -> int) <br><br>
  17. В основном docstring пишутся на английском. Например:
  18. <pre>
  19. <code>
  20. def module_level_function(param1, param2=None, *args, **kwargs):
  21. """This is an example of a module level function.
  22.  
  23. The format for a parameter is::
  24.  
  25. name (type): description
  26. The description may span multiple lines. Following
  27. lines should be indented. The "(type)" is optional.
  28.  
  29. Multiple paragraphs are supported in parameter
  30. descriptions.
  31.  
  32. Args:
  33. param1 (int): The first parameter.
  34. param2 (:obj:`str`, optional): The second parameter. Defaults to None.
  35. Second line of description should be indented.
  36. *args: Variable length argument list.
  37. **kwargs: Arbitrary keyword arguments.
  38.  
  39. Returns:
  40. bool: True if successful, False otherwise.
  41.  
  42. The return type is optional and may be specified at the beginning of
  43. the ``Returns`` section followed by a colon.
  44.  
  45. The ``Returns`` section may span multiple lines and paragraphs.
  46. Following lines should be indented to match the first line.
  47.  
  48. The ``Returns`` section supports any reStructuredText formatting,
  49. including literal blocks::
  50.  
  51. {
  52. 'param1': param1,
  53. 'param2': param2
  54. }
  55.  
  56. Raises:
  57. AttributeError: The ``Raises`` section is a list of all exceptions
  58. that are relevant to the interface.
  59. ValueError: If `param2` is equal to `param1`.
  60. """
  61. if param1 == param2:
  62. raise ValueError('param1 may not be equal to param2')
  63. return True
  64. </code>
  65. </pre>
  66. **_N.B._**: не забываем про аннотацию, в особенности когда определяется класс или комплексная функция !
  67.  
  68. ---
  69.  
Advertisement
Add Comment
Please, Sign In to add comment