python - 如何在 Python 3.9 中指定多个参数联合类型作为类型提示
问题描述
例如,如果我的代码在Python 3.10中是这样的:
from typing import Union
class TupleInvalid(Exception):
pass
TestValue = Union[int, str, float]
TestListA = tuple[str, TestValue]
TestListB = tuple[str, TestValue, TestValue]
def two_or_three(*tuples: TestListA | TestListB) -> str:
for x in tuples:
if isinstance(x[0], str):
if len(x) == 2:
return 'two'
elif len(x) == 3:
return 'three'
else:
raise TupleInvalid('Tuple should be 2 or 3 long')
else:
raise TupleInvalid(
'Tuple should be (<str>, <int | float | str>, \
<int | float | str> (optional)')
print(two_or_three(("test", 3, 4.5)))
print(two_or_three(("testing", 'hi')))
我的 linter 将能够了解参数*tuples
应该是一个由tuple[str, TestValue]
or组成的元组的事实tuple[str, TestValue, TestValue]
。然而,在 Python 3.9 中,它似乎无法工作。我试着让它成为一个,Union[TestListA, TestListB]
但这只会产生很多错误。(TypeError:无法实例化打字。联合)
使用or
不会给出任何错误,但我的 linter 似乎无法找到可能的第二种类型。
(*tuples: TestListA or TestListB)
解决方案
Python 3.9 没有这个特性。它是在 Python 3.10 中引入的。
推荐阅读
- flutter - 为什么我的 statefull 小部件在颤振中的 setState() 后无法正确重建?
- node.js - 找不到模块nodeJS
- php - 防止直接访问 php 文件 jquery load()
- javascript - 反向页面计算算法
- c - 如何将一组数字插入到链表中?
- mysql - 具有相同 ID 的 MySQL SUM 行
- python - Python:遍历循环和列表
- php - 如何使用 PHP 检查网页是否包含图像文件?
- android - 即使从 Firebase 获取浮点值后,Toast 仍显示值为 null
- sql - sql 在子集中创建序列号 - apache derby