-1

Basically, I want to create a function or decorator that checks that the type of every argument passed in a function is the same as the type hints specify, and displays appropriate errors if not.

This should be able to compare standard types, such as 'int', etc. as well as typing types, such as 'typing.Iterable'

It might look like this:

@checktypes
def some_function(arg1: str, arg2: int, arg3: Iterable) -> None:
    pass

some_function("string", 1, True)
# This should display an error like:
# TypeError: 'arg3' to 'some_function()' must be of type 'typing.Iterable', not type 'bool'
darragh
  • 11
  • 4

1 Answers1

0

Python is not meant to enforce strict typing, instead it popularized duck typing. What you want to do go against that, but you can do it.

To inspect a function's parameters annotations :

print(some_function.__annotations__)
{'arg1': <class 'str'>, 'arg2': <class 'int'>, 'arg3': typing.Iterable, 'return': None}

You can do that in your checktypes wrapper. Then compare the actual values with the expected types, for example :

isinstance([1, 2, 3], Iterable)  # True

In the end, it looks a lot like this answer to Python >=3.5: Checking type annotation at runtime.

Lenormju
  • 4,078
  • 2
  • 8
  • 22