Sitemap

Python Type Hinting and Speed

2 min readMar 24, 2020

--

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

Press enter or click to view image in full size
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

Press enter or click to view image in full size
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).

Press enter or click to view image in full size
Runtime profile

The program completed execution in approximately 0.705seconds.

FIBONACCI WITH TYPE HINTING

Using the same algorithm but with type hints.

Press enter or click to view image in full size

The program completed execution in approximately 0.708seconds.

Get Victor Adeyanju’s stories in your inbox

Join Medium for free to get updates from this writer.

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

--

--

Victor Adeyanju
Victor Adeyanju

Written by Victor Adeyanju

A software developer specialised in Python programming, Flutter, and intelligent systems engineering.