Python typing and validation with mypy and pydantic

Let’s make our Python code more readable with typing

Lynn G. 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…

--

--

Lynn G. Kwong

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