(` =~~/

Python's missing runtime type checker

Posted on

The typing module doesn't make python a statically typed language. The interpreter is still the same duck-typed goo that we all love.

The interpreter doesn't have any special knowledge about the types in the typing module. It semantically ignores all type annotations in code.

Take the following snippet -

names: typing.List[str] = ["guido", "tim", "barry"]

From the perspective of the interpreter, the object pointed to by names is a list. There's no discrimination based on the specific container type. typing.List[typing.Any], typing.List[str] and typing.List[bool] are all the same list type, internally.

Which is the reason why the following, surprisingly, raises a TypeError -

isinstance(names, typing.List[str])

This is all very unfortunate. All that work spent on annotating thousands of lines of code, and its basically useless at runtime? (Well, except NamedTuple and friends)

Typeguard to the rescue!