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

妖精的绣舞 提交于 2020-07-18 15:56:49

问题


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"))

回答1:


Python 3 introduces function annotations. By themselves they don't do anything, but you can write your own enforcement:

def strict(fun):
    # inspect annotations and check types on call

@strict
def funcA(a: int, b: int) -> int:
    return a + b 



回答2:


In Python, a dynamically and strongly typed language, the type information of a function 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




回答3:


the best way is to use docstrings to store such information of the function and

In [49]: def funcA(a,b):
   ....:     ''' returns an int '''
   ....:     return int(a+b)
   ....:

In [50]: funcA.__doc__
Out[50]: ' returns an int '



回答4:


In Python return type is not known until the call is performed and return statement is executed. It even can be different in different situations, so a brief answer is "not possible".

If you need to know the return type for certain function, you still may wrap it into some type checking code that also may expose the return type. However, that would be rather unpythonic:

def declare_return_type(t):
    def decorator(f):
        def wrapper(*a, **kw):
            res = f(*a, **kw)
            assert isinstance(res, t)
            return res
        wrapper.return_type = t
        return wrapper
    return decorator

@declare_return_type(int)
def f(a, b):
    return a + b

print f.return_type

print f(1, 2) # ok
f('a', 'b') # Assertion error

UPD: You may do the same to parameter types and check them as well.




回答5:


no chance. since python uses duck typing, you could pass parameters of different types, e.g. int and int, str and str, etc. to funcA. there is no chance to tell what return type and parameter type can be without seeing actual parameters




回答6:


This is impossible - your own example proves it, imagine you call it this way:

funcA(1, 2)

You get 3, an Integer, but what about this:

funcA("Test", "Test")

You get "TestTest", a string! Python doesn't care about types, and no function is guaranteed to output a single type. This would also produce different results with floats or lists. Beyond that, you could also explicitly return different types of objects.

In general, this is a good thing. It means you don't need to worry about whether or not the type is right, just whether it's possible to do with the things you pass in. This makes Python extremely flexible.



来源:https://stackoverflow.com/questions/15200048/how-to-get-the-parameters-type-and-return-type-of-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!