How to get the parameters' type and return type of a function?

snow picture snow · Mar 4, 2013 · Viewed 10.3k times · Source

I'm trying to implement strong type genetic programming in python.

Is there something like these sample?

def funcA(a,b):
  return a + b
return_type(funcA)

output: <class 'Integer'>

and

def funcA(a,b):
  return a + b
parameter_type(funcA)

output: [<class 'Integer'>,<class 'Integer'>]

update:

I'm trying to generate python's expression and avoiding something cannot be evaluated like this:

funcA(20, funcA(True, "text"))

Answer

Brian C. picture Brian C. · May 4, 2018

In Python, a dynamically typed language, the type information of a function's parameters is required at runtime. In 3.3 and later, you can get the type of a function as follows:

from inspect import signature
def foo(a, *, b:int, **kwargs):
...     pass

sig = signature(foo)

str(sig)
'(a, *, b:int, **kwargs)'

str(sig.parameters['b'])
'b:int'

sig.parameters['b'].annotation
<class 'int'>

see https://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object