Python typing and validation with mypy and pydantic

Let’s make our Python code more readable with typing

Lynn Kwong
7 min readMay 3, 2021

--

Python is a dynamically typed programming language, which means the types are only checked at runtime and a variable is allowed to change its type over its lifetime, whereas a statically typed language like Java checks the types at compile time, and a variable is not allowed to change its type over its lifetime. On the other hand, Python is a strongly typed language because the types cannot be automatically converted at runtime. For example, you cannot have an addition calculation on integer 1 and string "2", while in a weakly typed language such as JavaScript such calculation is allowed.

Photo by Hitesh Choudhary (Python programming) from Unsplash.

Even though dynamic typing can make it faster to write Python code in the development stage, it is also very easy to introduce bugs and errors which can only be identified at runtime. Besides, with no type definitions, the code can be more difficult to read and maintain. For example, you need to read through a function to get to know what type of data would be returned by it. However, with type hints or type annotations, the return type of a function can be known immediately. Once a program is developed, you would rarely need to rewrite or redesign it. However, it is much more common that you or your colleagues need to read or maintain the code after some time. Therefore, making the code easier to read would be very important, especially if you work in a team where people have to review each other’s code.

Typing has become more and more important in Python and the type hint standards introduced in PEP484 make it possible and easy to add type annotations to your Python code. After type hints have been added to a Python file, the mypy library can be used to do static type checking before it is run. Besides, pydantic, a data validation library using Python type annotations, can enforce type hints at runtime and provide user-friendly errors when data is invalid.

How to add type hints to your Python code?

The typing system of Python is very similar to that of TypeScript, which is a strict syntactical superset of JavaScript and adds optional static typing to the language. Similar to the use cases in TypeScript, we normally only add types to functions and classes and don’t…

--

--

Lynn Kwong

I’m a Software Developer (https://superdataminer.com) keen on sharing thoughts, tutorials, and solutions for the best practice of software development.