Python >=3.5: Checking type annotation at runtime

Bertrand Caron picture Bertrand Caron · Apr 27, 2017 · Viewed 8.3k times · Source

Does the typing module (or any other module) exhibit an API to typecheck a variable at runtime, similar to isinstance() but understanding the type classes defined in typing?

I'd like to be to run something akin to:

from typing import List
assert isinstance([1, 'bob'], List[int]), 'Wrong type'

Answer

aravindsagar picture aravindsagar · Sep 6, 2019

I was looking for something similar and found the library typeguard. This can automatically do runtime type checks wherever you want. Checking types directly as in the question is also supported. From the docs,

from typeguard import check_type

# Raises TypeError if there's a problem
check_type('variablename', [1234], List[int])