[英]How can I type hint a variable that might contain a literal class
我正在向vertica_python
的存根添加一些类型提示。 其中一个函数在内部接受以下参数( cursor_type
):
def row_formatter(self, row_data):
if self.cursor_type is None:
return self.format_row_as_array(row_data)
elif self.cursor_type in (list, 'list'):
return self.format_row_as_array(row_data)
elif self.cursor_type in (dict, 'dict'):
return self.format_row_as_dict(row_data)
else:
raise TypeError('Unrecognized cursor_type: {0}'.format(self.cursor_type))
所以这个 function 需要 'list'、'dict'、类型列表或类型dict。 我想使用 Optional[Literal[list, dict, 'list', 'dict']],但不支持:
Type arguments for "Literal" must be None, a literal value (int, bool, str, or bytes), or an enum value
有什么办法可以实现我正在尝试的吗?
您可以将提示输入为Union[None, Type[list], Type[dict], Literal["list", "dict"]]
(从打字中导入 Union 和 Type)
请注意,因为这也会接受 list 或 dict 的子类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.