Python: Enforce Type Hints

To enforce Type Hints, copy the enforce_type function and import typing. Decorate your function with @enforce_type. The enforce_type function will raise a TypeError when it detects mismatched types or return the original function when matching types have been passed to the decorated function.

It requires decorated functions to include type hints.

import typing

def enforce_type(func):
    def wrapper_func(*args):
        # Get type hints from decorated function
        expected_types = typing.get_type_hints(func)
        # Build dictionary with comprehension with if evaluation
        type_errors = {arg: expected for arg, expected in zip(args, expected_types.values()) if type(arg) != expected}
        # Check for errors
        if len(type_errors) == 0:
            # If types match, return decorated function
            return func(*args)
            # Otherwise, raise TypeError
            error = "\tCheck {func}{args}: \t{errors}".format(func=func.__name__, args=args, errors=type_errors)
            raise TypeError(error)

    return wrapper_func

def test_func(a: int, b: int):
    return a + b

if __name__ == '__main__':
    # Whoops! The second argument should be an integer. Change "2" to 2 and run again.
    summed = test_func(1, "2")
> TypeError: 	Check test_func(1, '2'): 	{'2': <class 'int'>}

About the author

Shane Bellone

At the intersection of capricious and whimsy.

Add comment

By Shane Bellone