【问题标题】:Incompatible types in assignment (expression has type "List[<nothing>]", variable has type (...)赋值中的不兼容类型(表达式的类型为“List[<nothing>]”,变量的类型为 (...)
【发布时间】:2019-11-18 00:24:46
【问题描述】:

考虑以下独立示例:

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]]]")

这里有什么问题,我该如何正确注释这个例子?

【问题讨论】:

标签: python mypy


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-12-17
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多