【发布时间】:2020-09-14 21:02:02
【问题描述】:
有没有办法让这个工作
from typing import Literal
def foo(bar: Literal["bar"]) -> Literal["foo"]:
foo = "foo"
return foo
bar = "bar"
foo(bar)
这里是错误
foo.py:4: error: Incompatible return value type (got "str", expected "Literal['foo']")
foo.py:8: error: Argument 1 to "foo" has incompatible type "str"; expected "Literal['bar']"
很明显 foo 变量和 bar 是文字,因为它们被分配给文字,所以这是安全的,但 mypy 似乎没有跟踪这一点。有什么我遗漏的吗?
【问题讨论】:
-
我对Python类型的了解不多,但是一旦赋值给一个变量,我认为它不再是文字了;这是一个
str对象。