Docstring

Python 函式寫作

Shayne Miel

Software Architect @ Duo Security

複雜的函式

def split_and_stack(df, new_names):
  half = int(len(df.columns) / 2)
  left = df.iloc[:, :half]
  right = df.iloc[:, half:]
  return pd.DataFrame(
    data=np.vstack([left.values, right.values]),
    columns=new_names
  )
Python 函式寫作
def split_and_stack(df, new_names):
  """將 DataFrame 的欄分成左右兩半,垂直堆疊後,
  回傳以 `new_names` 為欄名的新 DataFrame。
  Args:

    df (DataFrame): 要分割的 DataFrame。
    new_names (iterable of str): 新 DataFrame 的欄名。
  Returns:

    DataFrame
  """
  half = int(len(df.columns) / 2)
  left = df.iloc[:, :half]
  right = df.iloc[:, half:]
  return pd.DataFrame(
    data=np.vstack([left.values, right.values]),
    columns=new_names
  )
Python 函式寫作

docstring 結構

def function_name(arguments):
  """
  函式用途的說明。

  參數說明(若有)。

  回傳值說明(若有)。

  可能拋出的錯誤說明(若有)。

  其他備註或使用範例(選用)。
  """
Python 函式寫作

Docstring 格式

  • Google 風格
  • Numpydoc
  • reStructuredText
  • EpyText
Python 函式寫作

Google 風格-描述

def function(arg_1, arg_2=42):
  """函式用途的說明。
  """
Python 函式寫作

Google 風格-參數

def function(arg_1, arg_2=42):
  """函式用途的說明。

  Args:
    arg_1 (str): 對 arg_1 的說明,必要時可換行。
    arg_2 (int, optional): 若有預設值,請標註 optional。
  """
Python 函式寫作

Google 風格-回傳值

def function(arg_1, arg_2=42):
  """函式用途的說明。

  Args:
    arg_1 (str): 對 arg_1 的說明,必要時可換行。
    arg_2 (int, optional): 若有預設值,請標註 optional。
  Returns:
    bool: 回傳值的可選說明。

    續行不需縮排。
  """
Python 函式寫作
def function(arg_1, arg_2=42):
  """函式用途的說明。

  Args:
    arg_1 (str): 對 arg_1 的說明,必要時可換行。
    arg_2 (int, optional): 若有預設值,請標註 optional。
  Returns:
    bool: 回傳值的可選說明。

    續行不需縮排。
  Raises:
    ValueError: 列出函式會刻意拋出的錯誤型別。

  Notes:
    See https://www.datacamp.com/community/tutorials/docstrings-python
    for more info.  

  """
Python 函式寫作

Numpydoc

def function(arg_1, arg_2=42):
  """
  函式用途的說明。

  Parameters
  ----------
  arg_1 : expected type of arg_1
    arg_1 的說明。
  arg_2 : int, optional
    若有預設值,請標註 optional。
    Default=42。

  Returns
  -------
  回傳值的型別
    可包含回傳值說明。
    若此函式為產生器,將「Returns」改為「Yields」。
  """
Python 函式寫作

取得 docstring

def the_answer():
  """回傳生命、
  宇宙與萬事萬物的答案。

  Returns:
    int
  """
  return 42

print(the_answer.__doc__)
Return the answer to life, 
  the universe, and everything.

  Returns:
    int
import inspect
print(inspect.getdoc(the_answer))
Return the answer to life, 
the universe, and everything.

Returns:
  int
Python 函式寫作

一起來練習吧!

Python 函式寫作

Preparing Video For Download...