Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
hancho Avatar asked Aug 09 '19 15:08

hancho


People also ask

Are type hints enforced in Python?

Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types. As the name says, type hints just suggest types.

How do type hints work in Python?

Python's type hints provide you with optional static typing to leverage the best of both static and dynamic typing. Besides the str type, you can use other built-in types such as int , float , bool , and bytes for type hintings. To check the syntax for type hints, you need to use a static type checker tool.

What is Typevar in Python?

It is a type variable. Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions.

What is MYPY Python?

“Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or 'duck') typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking.” A little background on the Mypy project.


1 Answers

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.

like image 62
Christopher Peisert Avatar answered Oct 26 '22 01:10

Christopher Peisert