Last modified: Sep 10, 2026

Enforce Types in Python

Python is a dynamically typed language. This means variables do not have fixed types. You can assign any value to a variable at any time. While this offers flexibility, it can lead to unexpected errors during runtime.

Type enforcement helps avoid such issues. It ensures that functions and variables use the correct data types. Python provides several ways to enforce types. These include type hints, runtime checks, and external libraries.

Why Enforce Types?

Enforcing types improves code reliability. It catches bugs early in development. It also enhances code readability. Other developers can understand expected inputs and outputs easily.

Consider a function that adds two numbers. If a string is passed by mistake, the result may be unexpected. Type enforcement prevents such scenarios.

Using Type Hints

Type hints are the standard way to specify expected types in Python. They were introduced in Python 3.5. Type hints do not enforce types at runtime. They act as documentation for developers and tools.

Here is an example of a function with type hints:


def add_numbers(a: int, b: int) -> int:
    return a + b

This function expects two integers and returns an integer. A type checker like mypy can verify these hints.

Runtime Type Checking

Sometimes you need to enforce types at runtime. You can do this manually using isinstance().

Here is an example:


def add_numbers(a: int, b: int) -> int:
    if not isinstance(a, int) or not isinstance(b, int):
        raise TypeError("Both arguments must be integers")
    return a + b

If non-integer values are passed, a TypeError is raised.


>>> add_numbers(3, 5)
8
>>> add_numbers("3", 5)
TypeError: Both arguments must be integers

Using Pydantic for Type Enforcement

Pydantic is a powerful library for data validation. It enforces types using Python type hints. It is widely used in APIs and data processing.

First, install Pydantic:


pip install pydantic

Here is an example of a Pydantic model:


from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

user = User(name="Alice", age="30")
print(user.age)

Pydantic automatically converts the string "30" to an integer.


30

Invalid data raises a validation error:


user = User(name="Bob", age="not a number")

pydantic.error_wrappers.ValidationError: 1 validation error for User
age
  value is not a valid integer (type=type_error.integer)

Enforcing Types with Decorators

You can create custom decorators to enforce types. This approach combines type hints with runtime checks.

Here is an example:


import functools

def enforce_types(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        annotations = func.__annotations__
        for arg, value in zip(func.__code__.co_varnames, args):
            if arg in annotations:
                expected_type = annotations[arg]
                if not isinstance(value, expected_type):
                    raise TypeError(f"Argument '{arg}' must be {expected_type}")
        return func(*args, **kwargs)
    return wrapper

@enforce_types
def greet(name: str, times: int) -> str:
    return (f"Hello, {name}! " * times).strip()

This decorator checks each argument against its type hint.


>>> greet("Alice", 3)
'Hello, Alice! Hello, Alice! Hello, Alice!'
>>> greet("Alice", "3")
TypeError: Argument 'times' must be 

Choosing the Right Approach

Select the method that fits your needs:

  • Type hints are great for documentation and static analysis.
  • Runtime checks catch errors during execution.
  • Pydantic is ideal for complex data validation.
  • Custom decorators offer reusable enforcement logic.

Conclusion

Enforcing types in Python adds structure to your code. It reduces bugs and improves maintainability. Whether you use type hints, runtime checks, or libraries like Pydantic, each method has its strengths.

Start by adding type hints to your functions. Then, use tools like mypy to check them. For runtime safety, consider decorators or Pydantic. These practices make your Python code more robust and professional.