Literal["foo"]: foo = "foo-6ren">
gpt4 book ai didi

python - mypy 可以跟踪字符串文字吗?

转载 作者:行者123 更新时间:2023-12-04 02:31:34 24 4
gpt4 key购买 nike

有没有办法让这项工作

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 似乎没有跟踪这个。有什么我想念的吗?

最佳答案

MyPy 将文字推断为它们的内置类型,而不是 Literal他们的值(value)。

mypy Docs » Literal types

You must explicitly add an annotation to a variable to declare that it has a literal type. [..] variables without this annotation are not assumed to be literals.


允许推断 Literal值,将变量注释为 Final :
from typing import Final

from typing_extensions import Final

bar: Final = "bar"
reveal_type(bar) # Revealed type is 'Literal['bar']?'
将变量注释为 Final表示它的值不会被类似类型的值替换。这使得将类型推断为特定的 Literal 是正确的。值,而不仅仅是一般类型。
请注意,此推断是上下文相关的:类型推断为 Literal对于 Literal 的所有情况是期待。对于需要类型的情况,无论是文字类型、基类型还是 TypeVar,都会将该类型推断为通用类型。
reveal_type([bar])  # Revealed type is 'builtins.list[builtins.str*]'

关于python - mypy 可以跟踪字符串文字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63891789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com