7

次のような Google スタイルのドキュメント文字列を作成するために使用される構文を認識しています。

def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    `PEP 484`_ type annotations are supported. If attribute, parameter, and
    return types are annotated according to `PEP 484`_, they do not need to be
    included in the docstring:

    Args:
        param1 (int): The first parameter.
        param2 (str): The second parameter.

    Returns:
        bool: The return value. True for success, False otherwise.

    """

しかし、実行されるコードの分岐に応じて複数の型を返すことができる関数がある場合はどうなるでしょうか? これを文書化する適切な方法は何でしょうか?

以下に例を示します。パーツには何を入れる必要がありReturnsますか?

def foo(x, y):
    """Dummy function.

    Args:
        x (int): integer
        y (int): integer

    Returns:
        list/dict: either list or a dict depending on...

    """
    if x > y:
        return [1, 2, 3]
    if x < y:
        return {1:2}

2 つの異なる戻り値の型を示すがあります。

def add2(a, b):
    """Add numbers or concatenate strings.

    Args:
      a (int/str): String or integer to be added
      b (int/str): String or integer to be added

    Returns:
      int/str: Result
    """
    pass

ただし、ナポレオンがネイティブでサポートし、ドキュメントを読みやすくするために、タイプと説明の両方を提供する最良の方法は何でしょうか。

int/str: %description%複数の戻り値の型を処理する唯一の方法は使用ですか?

    Returns:
      int/str: integer if a > b and a string otherwise
4

2 に答える 2

2

注釈を使用して、関数の結果に応じて異なる型の戻り値の型を指定する場合は、次の方法で実行できます。

from typing import Type, Dict, Optional

def function(self) -> Optional[dict, str]:
    if self.result:
        return self.result
    else:
        return "Empty result"

詳細はこちら

于 2020-04-04T03:36:27.720 に答える