Type hinting in python

Jimmy (xiaoke) Shen
2 min readApr 19, 2020

Why this article?

Type hinting is introduced to Python since python 3.6. In this article, I’d like to find answers to the following questions.

  1. Why type hinting?
  2. When should we use type hinting?
  3. Can type hinting speed up the python code execution time?
  4. What is mypy?
  5. Can I only use mypy to better support type hinting?
  6. What is a good resource for me to study type hinting?
  7. Type hinting cheatsheet

What is mypy?

Based on the official website of mypy ,

“Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or “duck”) typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking. Mypy type checks standard Python programs; run them using any Python VM with basically no runtime overhead.”

About what is duck typing in python, please read this article.

What is a good resource for me to study type hinting?

Type hinting cheatsheet

Awesome live coding from [3]

From this live coding, not only you can use how Joel Grus is using type hinting, but also you can learn how to build a Pytorch like deep learning framework from scratch, isn't it cool?

This article is incomplete, I will keep on update it.

How to use NamedTuple

For NamedTuple, we can following the below way[5].

from typing import NamedTuple

class Point(NamedTuple):
x: int
y: int = 1 # Set default value

Point(3) # -> Point(x=3, y=1)

Recall how to use namedtuple without type checking.

>>> from collections import namedtuple>>> Point = namedtuple('Point', 'x y')>>> pt1 = Point(1.0, 5.0)>>> pt2 = Point(2.5, 1.5)>>> pt1Point(x=1.0, y=5.0)>>> pt1.x1.0>>> pt1[0]1.0

Put quotes around the type or not

Two links to talk about this:

  1. StackOverflow
  2. forward reference

Difference between Optional and Union

Callable

How to run mypy to ignore missing imports

mypy autograd/ --ignore-missing-imports

Reference

[1]https://realpython.com/python-type-checking/#static-typing

[2]http://mypy-lang.org/

[3]https://github.com/joelgrus/autograd/blob/master/README.md

[4]https://medium.com/@jim.morris.shen/watch-here-upcoming-mles-f811c6c3689d?source=friends_link&sk=1e39e80f8a2a9bcc612a2cf1b4739aa3

[5]https://stackoverflow.com/questions/34269772/type-hints-in-namedtuple

--

--