赋值中的类型不兼容(表达式的类型为“List[<nothing>]”,变量的类型为 (...)

d33*_*tah 7 python mypy

考虑以下独立示例:

from typing import List, Union

T_BENCODED_LIST = Union[List[bytes], List[List[bytes]]]
ret: T_BENCODED_LIST = []
Run Code Online (Sandbox Code Playgroud)

当我用 mypy 测试它时,出现以下错误:

from typing import List, Union

T_BENCODED_LIST = Union[List[bytes], List[List[bytes]]]
ret: T_BENCODED_LIST = []
Run Code Online (Sandbox Code Playgroud)

这里有什么问题以及如何正确注释这个示例?

JGC*_*JGC 6

这与以下 mypy 错误有关:

Union该问题与空列表的使用有关。

有两种方法可以解决这个问题:

  1. 让 mypy 忽略空列表分配(不理想,但可能是最简单的方法)
  2. 使用类型提示函数执行空列表赋值

方法 1 - 让 mypy 忽略空列表分配

from typing import List, Union

# Define the variable with type hint
T_BENCODED_LIST: Union[List[bytes], List[List[bytes]]]

# Set the value to empty list and tell mypy to look the other way.
T_BENCODED_LIST = []  # type: ignore
Run Code Online (Sandbox Code Playgroud)

这感觉像是一个合理的方法,因为它允许 mypy 继续假设类型已正确定义。

方法 2 - 使用类型提示函数进行空列表赋值

使用类型提示函数可以避免Union列表为空的问题。这种方法意味着添加仅解决打字问题所需的代码,因此不是我的首选方法。

from typing import List, Union

# Define the variable with type hint
T_BENCODED_LIST: Union[List[bytes], List[List[bytes]]]

# Create a type-hinted function that can be used
# for assignment.
def get_empty_list_bytes() -> List[bytes]:
    return []

# Set the value to empty list using the function.
# Mypy will assume the type based on the functions type hint.
T_BENCODED_LIST = get_empty_list_bytes()
Run Code Online (Sandbox Code Playgroud)