Python 类型提示(注解)是否会导致一些 运行 时间效应?
Does Python type hint (annotations) cause some run-time effects?
Python 函数注释和类型提示 (PEP 3107 and PEP 484) 是否会造成一些 运行 时间效应?
它能让代码更快吗?或者减少内存的使用?否则会使代码变慢?
根据 non-goals in the PEP 484 documentation,类型检查和性能优化取决于 third-party 工具或留给程序员。
简而言之:不,它们不会造成任何 run-time 影响,除非您明确使用它们。
类型提示和注解确实提供了可以由第 3 方工具传递的属性(参见 typing.get_type_hints
),但原生 CPython 不会在 运行 时对这些进行类型检查,因此这应该不会影响代码性能显着与注释不同。我 运行 一些使用 timeit
和删除类型提示的测试在 运行 时的影响可以忽略不计(无法与背景 噪声 区分开来),所以任何对性能的担忧肯定是过早优化的严重情况。
来自PEP 484:
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 函数注释和类型提示 (PEP 3107 and PEP 484) 是否会造成一些 运行 时间效应?
它能让代码更快吗?或者减少内存的使用?否则会使代码变慢?
根据 non-goals in the PEP 484 documentation,类型检查和性能优化取决于 third-party 工具或留给程序员。
简而言之:不,它们不会造成任何 run-time 影响,除非您明确使用它们。
类型提示和注解确实提供了可以由第 3 方工具传递的属性(参见 typing.get_type_hints
),但原生 CPython 不会在 运行 时对这些进行类型检查,因此这应该不会影响代码性能显着与注释不同。我 运行 一些使用 timeit
和删除类型提示的测试在 运行 时的影响可以忽略不计(无法与背景 噪声 区分开来),所以任何对性能的担忧肯定是过早优化的严重情况。
来自PEP 484:
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.