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

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

问题描述

Python可以注释功能并键入提示吗?( PEP 3107 PEP 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 )可以由第三方工具传递,但本机CPython在运行时不会进行类型检查,因此这不会以与注释相同的方式显着影响代码性能. t.我用timeit进行了一些测试,删除类型提示对运行时的影响可忽略不计(与背景 noise 区别不大),因此,对性能的任何担忧肯定是过早优化的严重案例.

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天全站免登陆