我如何记录:rtype:对于一个返回多种可能数据类型的函数?

时间:2016-06-01 13:50:07

标签: python return-type restructuredtext docstring

在Python文档字符串中,如何为可以返回多种可能数据类型的函数记录:rtype:

例如,如果一个函数可以返回defaultdict OR dict OR list,根据函数参数,你如何记录这个?

代码示例:

from collections import defaultdict

def read_state(state_file, state_file_type='defaultdict'):
    """Deserialize state file or create empty state and return it.

    :param state_file: The path and file name of state file to read.
    :type state_file: str
    :param state_file_type: Data type in which state is stored.
    :type state_file_type: str
    :return: Current or new empty state.
    :rtype: ????? 
    """
    if os.path.exists(state_file):
        with open(state_file) as conf_fo:
            state = json.load(conf_fo)
    elif state_file_type == 'defaultdict':
        state = defaultdict(lambda: defaultdict(list))
    elif state_file_type == 'dict':
        state = {}
    elif state_file_type == 'list':
        state = []
    else:
        raise TypeError("State file type not defined.")
    return state

2 个答案:

答案 0 :(得分:12)

您可以在rtype

中明确使用'或'
:rtype: collections.defaultdict or dict or list

变体

:rtype: collections.defaultdict | dict | list

答案 1 :(得分:9)

我想我刚发现自己遇到了类似的问题:JBOSS documentation

:rtype:可以

:rtype: Union[collections.defaultdict, dict, list]