The typing module added in Python 3.5 (see reference docs here) adds additional types and meta-types to allow for more control over python type hints. In this post we’ll talk about what this module adds and what neat things you can do with it.

This is the third post in a multi-part series on typing in Python.

  1. Introduction to Python Types
  2. Python Type Hinting

General Overview

The following types are new in this module and require importing them from the typing module (available in python3.5+) before using.

  • Any
  • Union
  • Tuple
  • Callable
  • List

This module also adds the functionality to alias types and create new types.

There are also equivalent types for every native type that exist solely for the purpose of type-checking and hinting.

How to Check Types (the Pythonic Way)

Soooo, technically the following code snippet works, but isn’t Pythonic.

The better way to check this is to use isinstance and issubclass

For more information see this SO post.

For these examples however, we’ll use enforce to check the types. Feel free to run the examples and verify the results.

The Any Type

Everything is of the Any type. Everything.

The Union Type

This type allows for an object to be either one type or the other.

The Tuple Type

The Tuple type models exactly what tuples do in python, immutable ordered collections.

The Callable Type

This is for typing functions and other callable items.

The List Type

As with Tuple, this is the type for python lists.

Other Types

There are a ton of other official types introduced in this module with the purpose of typing functions more accurately. They all have fairly intuitive usages, which is why I’m not going through and listing all of them. For a full list check the reference docs here.

Leave a Reply

Your email address will not be published. Required fields are marked *