1.6. Typing#

1.6.1. Enforce types with typeguard#

How to enforce types in Python easily?

You can try type hinting and define the expected types.

But you can still pass the wrong types and get away without an error.

Instead, use typeguard.

typeguard’s decorator makes sure that an error gets raised when a variable of a wrong type is passed.

See below, how you only need to add a decorator to the function to make things work.

!pip install typeguard
from typeguard import typechecked

@typechecked
def say_hello(name: str):
    print(f"Hello, {name}")
    

say_hello(3)

1.6.2. Static type checking with mypy#

Do you want to catch type errors before they cause problems in production?

Try mypy!

mypy is a static type checker for Python that can help you catch type errors before you even run your code.

It analyzes your code to ensure that the types of your variables and functions align with the expected types.

So mypy helps you to write more reliable code.

# bank.py
def deposit(amount: int, balance: int):
        return balance + amount
    
def withdraw(amount: int, balance: int):
        return balance - amount
    

deposit(100, 1000)
withdraw(100, "1000")    
!pip install mypy
!mypy bank.py

1.6.3. Faster Static Type Checking with pyright#

Do you wish to find type errors before they make problems in production?

Use pyright!

pyright is a fast static type checker for Python, which helps you find type errors even before you run your code.

It checks your code to make sure that the types of your variables and functions match what is expected.

pyright is written in TypeScript, so check the community version to avoid going through installing extra things (Link is below).

It’s 3x-5x times than the OG static type checker, mypy.

Whether it’s pyright or mypy, please consider to integrate static type checkers.

!pip install pyright
!pyright