mypy 可以跟踪字符串文字吗? [英] Can mypy track string literals?

查看:60
本文介绍了mypy 可以跟踪字符串文字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何要完成这项工作

Is there anyway to make this work

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 似乎没有跟踪这一点.有什么我遗漏的吗?

Is pretty obvious that foo variable and bar are literals because they are assigned to literals, so this is safe, but mypy seems to not track this. Is there anything that I'm missing?

推荐答案

MyPy 将文字推断为它们的内置类型,而不是它们的值的 Literal.

MyPy infers literals to their builtin type, not a Literal of their 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:

To allow inference of Literal values, annotate the variable as Final:

from typing import Final

from typing_extensions import Final

bar: Final = "bar"
reveal_type(bar)  # Revealed type is 'Literal['bar']?'

将变量注释为 Final 表示它的值不会替换为类似类型的值.这使得将类型推断为特定的 Literal 值是正确的,而不仅仅是一般类型.

Annotating a variable as Final indicates that its value will not be substituted for a value of similar type. This makes it correct to infer the type as the specific Literal value, instead of just the general type.

请注意,此推断是上下文相关的:对于需要 Literal 的所有情况,类型都被推断为 Literal.对于需要类型的情况,无论是文字类型、基类型还是 TypeVar,类型都被推断为通用类型.

Note that this inference is contextual: The type is inferred as Literal for all cases where a Literal is expected. For cases in which a type is expected, be it the literal type, a base type or TypeVar, the type is inferred as the general type.

reveal_type([bar])  # Revealed type is 'builtins.list[builtins.str*]'

这篇关于mypy 可以跟踪字符串文字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆