如何获取函数参数类型和返回类型?
我正在尝试在Python中实现强类型的遗传编程。
有没有类似于这些示例的东西呢?
def funcA(a,b):
return a + b
return_type(funcA)
output: <class 'Integer'>
还有
def funcA(a,b):
return a + b
parameter_type(funcA)
output: [<class 'Integer'>,<class 'Integer'>]
更新:
我想生成Python的表达式,并且避免生成一些无法被计算的内容,比如这个:
funcA(20, funcA(True, "text"))
7 个回答
13
你可以通过注释来检查这个:
>>> def func(a: str) -> int:
# code
>>> func.__annotations__["return"]
<class 'int'>
参数也是一样:
>>> func.__annotations__["a"]
<class 'str'>
18
在Python这门动态类型的语言中,函数参数的类型信息是在运行时才需要的。从3.3版本开始,你可以这样获取一个函数的类型:
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'>
可以查看 https://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object
8
Python 3 引入了函数注解。单独来看,它们并没有什么实际作用,但你可以自己编写代码来强制执行这些注解的规则。
def strict(fun):
# inspect annotations and check types on call
@strict
def funcA(a: int, b: int) -> int:
return a + b