为什么 mypy 不接受 list[str] 作为 list[Optional[str]]?

Why does mypy not accept a list[str] as a list[Optional[str]]?

示例 1:

from typing import List, Optional

def myfunc() -> List[Optional[str]]:
    some_list = [x for x in "abc"]
    return some_list

Mypy complains 在示例 1 中:

Incompatible return value type (got "List[str]", expected "List[Optional[str]]")

但是,这个例子gets no complaint:

示例 2:

def myfunc() -> List[Optional[str]]:
    some_list = [x for x in "abc"]
    return list(some_list)

不一致行为的解释是什么?

因为在 Python 中列表是不变的(参见示例 here and here)。

如果我们将 List[str] 传递给期望 List[Optional[str]] 的人,那么有人可能会在我们的列表中添加 None 并打破我们的假设。第二个例子是有效的,但是 return 语句中 list() 的输出没有保存在任何地方,没有人可以依赖 returned 值被非法改变。