有没有办法在Python中检查函数的签名?

mju*_*ewu 13 python

我正在寻找一种方法来检查给定函数在Python中使用的参数数量.目的是实现一种更健壮的方法来修补我的类以进行测试.所以,我想做这样的事情:

class MyClass (object):
    def my_function(self, arg1, arg2):
        result = ... # Something complicated
        return result

def patch(object, func_name, replacement_func):
    import new

    orig_func = getattr(object, func_name)
    replacement_func = new.instancemethod(replacement_func, 
                           object, object.__class__)

    # ...
    # Verify that orig_func and replacement_func have the 
    # same signature.  If not, raise an error.
    # ...

    setattr(object, func_name, replacement_func)

my_patched_object = MyClass()
patch(my_patched_object, "my_function", lambda self, arg1: "dummy result")
# The above line should raise an error!
Run Code Online (Sandbox Code Playgroud)

谢谢.

car*_*arl 15

您可以使用:

import inspect
len(inspect.getargspec(foo_func)[0])
Run Code Online (Sandbox Code Playgroud)

这不会确认可变长度参数,例如:

def foo(a, b, *args, **kwargs):
    pass
Run Code Online (Sandbox Code Playgroud)


Tah*_*lor 5

inspect.getargspec 在 Python 3 中已弃用。请考虑以下内容:

import inspect
len(inspect.signature(foo_func).parameters)
Run Code Online (Sandbox Code Playgroud)