How do I document :rtype: for a function that returns multiple possible data types? [duplicate]

泄露秘密 提交于 2019-12-20 19:47:06

问题


In a Python docstring how should one document the :rtype: for a function that can return multiple possible data types?

For example, if a function can return defaultdict OR dict OR list, based on the functions parameters, how do you document this?

Code example:

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

回答1:


You can use 'or' explicitly in the rtype

:rtype: collections.defaultdict or dict or list

variant

:rtype: collections.defaultdict | dict | list



回答2:


I think I just found out myself by stumbling over a similar question: How to specify multiple return types using type-hints

:rtype: can be

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


来源:https://stackoverflow.com/questions/37570679/how-do-i-document-rtype-for-a-function-that-returns-multiple-possible-data-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!