aeveris
aeveris

Reputation: 39

Is there a way to get the types of a functions arguments?

Let's say we have a function foo(a, b) that is part of the public API of a python module.
Is there any way to query the types of a and b that the function expects?
I know that I can get the number of arguments and their default values via the inspect module, but is there any type information available?

Upvotes: 2

Views: 63

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121534

Python is a dynamically typed language, so no; a function should document their expectations instead.

Python 3.5 and newer support optional type hinting; if the library uses type hints, then you can query this information with the typing.get_type_hints() function to access that information programatically.

Generally, Python functions should accept objects that implement expected functionality, not specific types. If your function iterates over a sequence to extract strings, then it should be documented as accepting (in type hinting terms) a Iterable[str] object, not a list or tuple or other specific type.

Upvotes: 6

Related Questions