How to get function arguments type?

Viewed 122

For example I have foo(...):

def foo(arg1: str, arg2: int, ...):
    ...

And I want to get this:

{'arg1': str, 'arg2': int, ...}

Please share with me if anyone knows anything about the answer.

1 Answers

This can be accessed via the __annotations__ attribute of a function object for Python versions >= 3.0:

type_annotation_dict = foo.__annotations__

Which should directly result in a dictionary mapping the parameter names to their type annotations:

{'arg1': str, 'arg2': int}

See also PEP 3107.

Additionally, the typing standard library module has a function get_type_hints which provides some additional functionality. See the Python docs on this function for more information.

Related