Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get types of arguments in python

I'm learning python. I like to use help() or interinspect.getargspec to get information of functions in shell. But is there anyway I can get the argument/return type of function.

like image 868
leon Avatar asked Feb 09 '10 06:02

leon


2 Answers

In the 3.4.2 documentation https://docs.python.org/3/library/inspect.html, there is a mention of what you exactly need (namely getting the types of arguments to a function).

You will first need to define your function like this:

def f(a: int, b: float, c: dict, d: list, <and so on depending on number of parameters and their types>):

Then you can use formatargspec(*getfullargspec(f)) which returns a nice hash like this:

(a: int, b: float)
like image 145
Venky Avatar answered Oct 29 '22 09:10

Venky


If you mean during a certain call of the function, the function itself can get the types of its arguments by calling type on each of them (and will certainly know the type it returns).

If you mean from outside the function, no: the function can be called with arguments of any types -- some such calls will produce errors, but there's no way to know a priori which ones they will be.

Parameters can be optionally decorated in Python 3, and one possible use of such decoration is to express something about the parameters' types (and/or other constraints on them), but the language and standard library offer no guidance on how such decoration might be used. You might as well adopt a standard whereby such constraints are expressed in a structured way in the function's docstring, which would have the advantage of being applicable to any version of Python.

like image 39
Alex Martelli Avatar answered Oct 29 '22 10:10

Alex Martelli