我有来自typing
的注释,但没有实例。我需要执行动态分析(没有对象实例(,以确保输出类型annotation与输入annotation兼容。
以下示例:
from typing import *
# Output -> Input
List[str] -> List[Union[str, int]] # ok
List[int] -> List[str] # not ok
Dict[str, str] -> Dict[str, Any] # ok
Dict[str, List[int]] -> Dict[str, List[Union[float, int]]] # ok
Dict[str, List[int]] -> Dict[str, List[str]]] # not ok
List[str] -> Iterator[str] # ok
我已经研究过typeguard
,但是它需要一个实例。在我的情况下,我还没有创建实例。
下面是一个摘要如何使用的示例。输出由Class1
创建,然后由Class2
用作输入。
from typing import *
class Class1:
output: List[str]
class Class2:
input: List[Union[str, bytes]]
这里的目的是检查Class1
产生的输出是否可以被Class2
输入所消耗。每个类都有object.__annotations__
下的注释,所以我们可以访问它们。
如何在不陷入if/else嵌套地狱的情况下实现这一目标,你有什么建议或更好的想法吗?非常感谢。
使用mypy
假设file.py
包含内容:
from typing import List, Union
def f(xs) -> List[int]:
...
def g(xs: List[Union[str, int]]) -> List[int]:
...
def h(xs: List[str]) -> List[str]:
...
a = g(f(...))
b = h(f(...))
并运行mypy file.py
,我们得到:
file.py:16: error: Argument 1 to "g" has incompatible type "List[int]"; expected "List[Union[str, int]]"
lpheno/blah.py:16: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
lpheno/blah.py:16: note: Consider using "Sequence" instead, which is covariant
lpheno/blah.py:17: error: Argument 1 to "h" has incompatible type "List[int]"; expected "List[str]"
Found 2 errors in 1 file (checked 1 source file)