如何进行仅类型注释的类型断言? [英] How to make type-annotation-only type assertions?
问题描述
我有两个功能:
def get_foo(params) -> Optional[str]
def bar(foo: str)
还有一个将这些函数链接在一起的函数:
And a function which chains these functions together:
def f(params):
# other stuff up here
foo = get_foo(params)
return bar(foo)
根据我的函数中发生的其他事情,我知道 get_foo
的结果 永远 不会是 None.
I know based on the other things happening in my function that the result of get_foo
will never be None.
当我针对这个文件运行 mypy
时,我当然得到错误:
When I run mypy
against this file, I of course get errors:
error: Argument 1 of "bar" has incompatible type "Optional[str]"; expected "str"
这是有道理的.
我可以添加一个 assert foo is not None
语句,但这是热路径代码,在我的测试中它具有可衡量的性能影响.我只想对 mypy 进行类型断言.我该怎么做?
I could add an assert foo is not None
statement, but this is hot-path code and in my tests it has measurable performance impact. I would like to make a type assertion for mypy only. How do I do that?
我也尝试在赋值语句后添加注释 #type: str
,但这产生了类似的错误
I also tried adding a comment #type: str
after the assignment statement, but this generated a similar error
推荐答案
您不会对此感到高兴.官方设计的向静态类型检查器断言值具有特定类型的方法是 typing.cast
,这是一个有实际运行时成本的实际函数,我相信 比你想要的 assert
更昂贵取代.它只是原封不动地返回它的参数,但它仍然有函数调用开销.Python 的类型注解系统没有设计成零开销的类型断言语法.
You're not going to be happy about this. The officially designed way to assert to static type checkers that a value has a specific type is typing.cast
, which is an actual function with a real runtime cost, I believe more expensive than the assert
you want to replace. It just returns its argument unchanged, but it's still got function call overhead. Python's type annotation system is not designed with a zero-overhead type assertion syntax.
作为替代方案,您可以使用 Any
作为逃生舱口".我相信如果您使用 Any
类型注释 foo
,mypy 应该允许 bar
调用.(我这里没有可用的 mypy,所以我没有检查.)局部变量注释没有运行时成本:
As an alternative, you could use Any
as an "escape hatch". I believe if you annotate foo
with type Any
, mypy should allow the bar
call. (I don't have mypy available here, so I haven't checked.) Local variable annotations have no runtime cost:
from typing import Any
def f(params):
foo: Any = get_foo(params)
return bar(foo)
除此之外,您最好的选择可能是使用 assert
并使用 -O
标志运行 Python,这会禁用断言.
Aside from that, your best option may be to use the assert
and run Python with the -O
flag, which disables asserts.
这篇关于如何进行仅类型注释的类型断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!