aeveris aeveris - 1 year ago 60
Python Question

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
that the function expects?

I know that I can get the number of arguments and their default values via the
module, but is there any type information available?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download