Python 类型提示(注释)是否会导致一些运行时影响? [英] Does Python type hint (annotations) cause some run-time effects?

查看:130
本文介绍了Python 类型提示(注释)是否会导致一些运行时影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Can Python 函数注释和类型提示(PEP 3107PEP 484) 会导致一些运行时影响吗?

Can Python function annotations and type hints (PEP 3107 and PEP 484) cause some run-time effects?

它能让代码更快吗?还是缩小内存使用量?否则它会使代码更慢?

Could it made the code faster? Or shrink the usage of memory? Or otherwise it would make code more slow?

推荐答案

类型提示和注释确实提供了属性(参见 typing.get_type_hints) 可以通过 3rd 方工具传递,但原生 CPython 不会在运行时进行类型检查,因此这不会显着影响代码性能与评论不同的方式相同.我使用 timeit 进行了一些测试,删除类型提示对运行时的影响可以忽略不计(无法与背景噪音区分开来),因此对性能的任何担忧肯定是过早优化的严重情况.

Type hints and annotations do provide attributes (see typing.get_type_hints) that can be passed by 3rd party tools but native CPython will not type check these at runtime, so this should not affect the code performance significantly in the same way that comments don't. I ran some tests with timeit and removing type hints had a negligible effect (not distinguishable from the background noise) on the run time, so any concerns about performance would certainly be a severe case of premature optimization.

来自 PEP 484:

虽然提议的打字模块将包含一些构建块运行时类型检查——特别是 get_type_hints() 函数-- 必须开发第三方包来实现特定的运行时类型检查功能,例如使用装饰器或元类.使用类型提示提高性能优化留给读者作为练习.

While the proposed typing module will contain some building blocks for runtime type checking -- in particular the get_type_hints() function -- third party packages would have to be developed to implement specific runtime type checking functionality, for example using decorators or metaclasses. Using type hints for performance optimizations is left as an exercise for the reader.

这篇关于Python 类型提示(注释)是否会导致一些运行时影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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