Python docstrings Formats

14 ก.ค. 2021

Python docstrings สามารถเขียนได้หลายรูปแบบมีให้เห็นได้ตามแหล่งต่างๆ อย่างไรก็ตาม รูปแบบที่ใช้หลักสำหรับ docstrings ดังต่อไปนี้

PEP-8

PEP-8 คือ official python coding standard ที่ประกอบด้วยหัวข้อเกี่ยวกับเอกสาร ซึ่งอ้างถึง PEP-257

ตัวอย่าง Documentation Strings

"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.
"""

Epytext

ในอดีต สไตล์ที่คล้ายกับ javadoc เป็นที่แพร่หลาย ดังนั้นจึงถูกใช้เป็นพื้นฐานสำหรับ Epydoc (ด้วยรูปแบบที่เรียกว่า Epytext) เพื่อสร้างเอกสาร

Example:

"""
This is a javadoc style.

@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""

reST

ปัจจุบันรูปแบบที่น่าจะแพร่หลายมากขึ้นคือ reStructuredText (reST) format ที่ใช้โดย Sphinx เพื่อสร้างเอกสาร
หมายเหตุ: มันถูกใช้เป็นค่าเริ่มต้นใน JetBrains PyCharm, มันถูกใช้เป็นค่าเริ่มต้นเป็นรูปแบบเอาต์พุตใน Pyment

Example:

"""
This is a reST style.

:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

- Google

google จะมี format ที่มักจะใช้งานเป็นของตัวเอง รูปแบบนี้ยังสามารถใช้งานใน Sphinx (ie. using Napoleon plugin) ได้ด้วย

Example:

"""
This is an example of Google style.

Args:
    param1: This is the first param.
    param2: This is a second param.

Returns:
    This is a description of what is returned.

Raises:
    KeyError: Raises an exception.
"""

Example Google Style Python Docstrings

Numpydoc

Numpy แนะนำให้ทำตาม numpydoc ของตนเองตามรูปแบบของ Google และใช้งานได้โดย Sphinx

"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.

Parameters
----------
first : array_like
    the 1st param name `first`
second :
    the 2nd param
third : {'value', 'other'}, optional
    the 3rd param, by default 'value'

Returns
-------
string
    a value in a string

Raises
------
KeyError
    when a key error
OtherError
    when an other error
"""

การ Converting และ Generating

เราสามารถที่จะให้ tool อย่างเช่น Pyment ในการ generate docstrings ใน Python project ที่ยังไม่มีเอกสารหรือสามารถ convert จาก project ที่มี docstrings แล้วไปเป็นเอกสารได้ จากรูปแบบไปสู่อีกรูปแบบหนึ่ง

หมายเหตุ: ตัวอย่างนำมาจาก Pyment documentation

Onyx

Just a middle-aged programmer, Can do many things but not the most.