Is there a way to check a function's signature

2020-08-09 11:22发布

I'm looking for a way to check the number of arguments that a given function takes in Python. The purpose is to achieve a more robust method of patching my classes for tests. So, I want to do something like this:

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!

Thanks.

标签: python
4条回答
爷、活的狠高调
2楼-- · 2020-08-09 11:44

You should use inspect.getargspec.

查看更多
手持菜刀,她持情操
3楼-- · 2020-08-09 11:48

The inspect module allows you to examine a function's arguments. This has been asked a few times on Stack Overflow; try searching for some of those answers. For example:

Getting method parameter names in python

查看更多
成全新的幸福
4楼-- · 2020-08-09 11:56

You can use:

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

This won't acknowledge variable-length parameters, like:

def foo(a, b, *args, **kwargs):
    pass
查看更多
我只想做你的唯一
5楼-- · 2020-08-09 12:06

inspect.getargspec is deprecated in Python 3. Consider something like:

import inspect
len(inspect.signature(foo_func).parameters)
查看更多
登录 后发表回答