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

2024-04-24 02:42:31 发布

您现在位置: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!

谢谢。


Tags: 方法nameselfnewobjectmydefmyclass
3条回答

你应该用^{}

您可以使用:

import inspect
len(inspect.getargspec(foo_func)[0])

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

def foo(a, b, *args, **kwargs):
    pass

^{}模块允许您检查函数的参数。这个问题在堆栈溢出时被问过几次;请尝试搜索其中的一些答案。例如:

Getting method parameter names in python

相关问题 更多 >