有没有办法检查函数';Python中的签名?
我正在寻找一种方法来检查Python中给定函数的参数数量。目的是实现一种更健壮的方法,为测试修补我的类。所以,我想这样做:有没有办法检查函数';Python中的签名?,python,Python,我正在寻找一种方法来检查Python中给定函数的参数数量。目的是实现一种更健壮的方法,为测试修补我的类。所以,我想这样做: class MyClass (object): def my_function(self, arg1, arg2): result = ... # Something complicated return result def patch(object, func_name, replacement_func): impor
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!
谢谢。您应该使用。该模块允许您检查函数的参数。关于堆栈溢出,这已经被问过几次了;尝试寻找其中一些答案。例如:
您可以使用:
import inspect
len(inspect.getargspec(foo_func)[0])
这不会确认可变长度参数,例如:
def foo(a, b, *args, **kwargs):
pass
Python3中不推荐使用
inspect.getargspec
。考虑一下:
import inspect
len(inspect.signature(foo_func).parameters)
“为测试修补我的类”?为什么不使用模拟对象?我不习惯使用mock。我“长大”了,打短发打补丁。我正在练习,弄清楚什么时候使用它,但与此同时,我还有项目要完成,还有测试要写:)。我明白了。在发布之前我做了一些搜索,但我想我应该使用更多的搜索词。抱歉打扰了,没问题。不过,最好向您指出其他答案,而不是在这里重复所有内容。