Search code examples
pythonruntimepython-typing

Raise an error if type hint is violated/ignored in Python?


After looking at this question I learned that the type hints are, by default, not enforced whilst executing Python code.

One can detect some discrepancies between the type hints and actual argument types using a slightly convoluted process of running pyannotate to generate stubs whilst running Python code, and scanning for differences after applying these stubs to the code.

However, it would be more convenient/faster to directly raise an exception if an incoming argument is not of the type included in the type hint. This can be achieved by manually including:

if not isinstance(some_argument, the_type_hint_type):
    raise TypeError("Argument:{argument} is not of type:{the_type_hint_type}")

However, that is quite labour intensive. Hence, I was curious, is it possible to make Python raise an error if a type-hint is violated, using an CLI argument or pip package or something like that?


Solution

  • The edit queue for the Answer by @Surya_1897 is full, hence I will include a more detailed description of the solution here.

    Typeguard does exactly what I was looking for. The following requirements apply:

    1. Install typeguard with:
    pip install typeguard
    
    1. Import typeguard into each script, and add the @typechecked property above each function.
    2. Example: Change:
    """Some file description."""
    
    def add_two(x:int):
        """Adds two to an incoming int."""
        return x+2
    somevar:float=42.1
    add_two(somevar)
    

    To:

    """Some file description."""
    from typeguard import typechecked
    
    
    @typechecked
    def add_two(x:int):
        """Adds two to an incoming int."""
        return x+2
    somevar:float=42.1
    add_two(somevar)
    

    The latter will than throw an err:

    TypeError: type of argument "x" must be int; got float instead