Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python type hint (annotations) cause some run-time effects? [duplicate]

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?

like image 583
Y.N Avatar asked Jan 17 '17 08:01

Y.N


People also ask

Does Python type hinting improve performance?

Type hints improve IDEs and linters. They make it much easier to statically reason about your code. Type hints help you build and maintain a cleaner architecture. The act of writing type hints forces you to think about the types in your program.

What does type hinting do Python?

PEP 484 introduced type hints — a way to make Python feel statically typed. While type hints can help structure your projects better, they are just that — hints — and by default do not affect the runtime.

Does Python enforce type hints?

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc. This module provides runtime support for type hints. The most fundamental support consists of the types Any , Union , Callable , TypeVar , and Generic .

What is type annotation Python?

What Are Type Annotations? Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.


1 Answers

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.

like image 95
Chris_Rands Avatar answered Oct 20 '22 14:10

Chris_Rands