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

Incompatible types in assignment (expression has type "List[<nothing>]", variable has type (...)

考虑以下独立示例:

from typing import List, Union

T_BENCODED_LIST = Union[List[bytes], List[List[bytes]]]
ret: T_BENCODED_LIST = []

用mypy测试时,出现如下错误:

example.py:4: error: Incompatible types in assignment (expression has type "List[<nothing>]", variable has type "Union[List[bytes], List[List[bytes]]]")

这里有什么问题,我怎样才能正确注释这个例子?

这与以下 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

这感觉是一种合理的方法,因为它允许 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()