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

时间:2010-08-20 20:57:05

标签: 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!

感谢。

4 个答案:

答案 0 :(得分:13)

您可以使用:

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

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

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

答案 1 :(得分:6)

您应该使用inspect.getargspec

答案 2 :(得分:2)

inspect模块允许您检查函数的参数。 Stack Overflow上曾多次询问过这个问题。尝试搜索其中的一些答案。例如:

Getting method parameter names in python

答案 3 :(得分:0)

现在不推荐使用

inspect.getargspec(至少在Python 3中)。考虑类似的东西:

import inspect
len(inspect.signature(foo_func).parameters)