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?
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?
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.
From 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.
class X(generic[int]
) is 3-5x times slower due to overriden __new__() method (fixed in pyhon3.9 by removing the method).. –
Stowers According to the non-goals in the PEP 484 documentation, type checking and performance optimization is dependent on third-party tools or left to the programmer.
So in short: no, they will not cause any run-time effects, unless you explicitly make use of them.
© 2022 - 2024 — McMap. All rights reserved.