hancho
hancho

Reputation: 1437

How to access Type Hints inside of a method after it's called in Python

I started implementing Type Hinting in a large code base worked on by multiple developers to increase transparency on what functions should expect as arguments.

What I would like to do is also validate that the arguments being passed to the function are the correct types.

This would be easy to do inside the function, but that doesn't seem pythonic. I want to make a utility that can be passed the args and types from the function and raises an exception if an incorrect type is passed for the corresponding arg.

example:

def find_integer_sum(a: int, b: int):
    utility.validate_args(args, types)
    return a + b

What I want is to somehow pass the args and types to a function without needing to always manually insert utility.validate_args({a: int, b: int}) as that can get cumbersome.

Is there a way to access args with their type hints?

Upvotes: 11

Views: 6827

Answers (1)

Christopher Peisert
Christopher Peisert

Reputation: 24194

From the Python typing documentation, you may use typing.get_type_hints().

typing.get_type_hints(obj[, globals[, locals]])
Return a dictionary containing type hints for a function, method, module or class object.

This is often the same as obj.__annotations__. In addition, forward references encoded as string literals are handled by evaluating them in globals and locals namespaces. If necessary, Optional[t] is added for function and method annotations if a default value equal to None is set. For a class C, return a dictionary constructed by merging all the __annotations__ along C.__mro__ in reverse order.

Upvotes: 7

Related Questions