Skip to main content

Command Palette

Search for a command to run...

Python Type Hints and Speed

Published
2 min read

Python Type Hinting and Speed

Type Hints are annotations that specify the runtime type of value within your Python codes. This look statically typed, right?

Image for post

Image for post

This was specified in PEP 484 and introduced Python 3.5.

It’s intuitive to think there would be some performance (speed) improvement at runtime since statically typed languages do not intrinsically need to check data type during runtime. Right? Let’s check it out

We will be using the classical Fibonacci series to check whether type hinting improves performance.

FIBONACCI WITHOUT TYPE HINT

Image for post

Image for post

Fibonacci series without type hint.

The Fibonacci function would be called 10,000 times and the appending operation would be called 10,000 * 100 (the nth term).

Image for post

Image for post

Runtime profile

The program completed execution in approximately 0.705seconds.

FIBONACCI WITH TYPE HINTING

Using the same algorithm but with type hints.

Image for post

Image for post

The program completed execution in approximately 0.708seconds.

The execution times are very close and the difference might be caused by some CPU state.

It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.

Why Type Hints then?

Python core philosophy as summarized in Zen of Python include:

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Readability counts.

Type Hints in Python would provide more readability to both human and statistical tools.

This PEP[484] aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and (perhaps, in some contexts) code generation utilizing type information.

Readability COUNTS

139 views