有没有办法在不调用 TypeError 的情况下调用参数数量错误的 Python 函数?
当您使用错误数量的参数或使用不在其定义中的关键字参数调用函数时,您会收到 TypeError。 我想要一段代码来接受回调并根据回调支持的内容使用变量参数调用它。 一种方法是,对于回调cb
,使用cb.__code__.cb_argcount
和cb.__code__.co_varnames
,但我宁愿将其抽象为诸如 apply
之类的东西,但这仅适用于“适合”的参数。
例如:
def foo(x,y,z):
pass
cleanvoke(foo, 1) # should call foo(1, None, None)
cleanvoke(foo, y=2) # should call foo(None, 2, None)
cleanvoke(foo, 1,2,3,4,5) # should call foo(1, 2, 3)
# etc.
Python 中已经有类似的东西吗?还是我应该从头开始编写?
When you invoke a function with the wrong number of arguments, or with a keyword argument that isn't in its definition, you get a TypeError. I'd like a piece of code to take a callback and invoke it with variable arguments, based on what the callback supports. One way of doing it would be to, for a callback cb
, use cb.__code__.cb_argcount
and cb.__code__.co_varnames
, but I would rather abstract that into something like apply
, but that only applies the arguments which "fit".
For example:
def foo(x,y,z):
pass
cleanvoke(foo, 1) # should call foo(1, None, None)
cleanvoke(foo, y=2) # should call foo(None, 2, None)
cleanvoke(foo, 1,2,3,4,5) # should call foo(1, 2, 3)
# etc.
Is there anything like this already in Python, or is it something I should write from scratch?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以检查函数的签名,而不是自己深入研究细节 - 您可能需要
inspect.getargspec(cb)
。我并不完全清楚您想要如何使用该信息以及您拥有的参数来“正确”调用该函数。 为简单起见,假设您只关心简单的命名参数,并且您想要传递的值位于 dict
d
中...也许您想要一些更奇特的东西,并且可以详细说明到底是什么?
Rather than digging down into the details yourself, you can inspect the function's signature -- you probably want
inspect.getargspec(cb)
.Exactly how you want to use that info, and the args you have, to call the function "properly", is not completely clear to me. Assuming for simplicity that you only care about simple named args, and the values you'd like to pass are in dict
d
...Maybe you want something fancier, and can elaborate on exactly what?
这也许?
编辑您的用例
This maybe?
Edit Your use cases