gpt4 book ai didi

python - 我如何记录 :rtype: for a function that returns multiple possible data types?

转载 作者:太空狗 更新时间:2023-10-29 17:26:53 27 4
gpt4 key购买 nike

<分区>

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

例如,如果一个函数可以根据函数参数返回 defaultdictdictlist,您如何记录这一点?

代码示例:

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com