Python功能的部分包装器
给定以下代码,
def myfunc(a=None, b=None, c=None, **kw):
func(arga=a, argb=b, **kw)
#do something with c
def func(arga=None, argb=None, argc=None):
....
我可以复制func
的签名的一部分,即丢失的args,而无需模仿func
的每个缺失的ARG?
简而言之,我想在myfunc的关键字中查看argc
,以使myfunc?
会有所不同。它将包含ARGC。 myFunc(a = none,b = none,c = none,argc = none)
@functools.wraps
允许包装完整的功能。使用部分
可以减去args。但不知道要添加。
Given the following code,
def myfunc(a=None, b=None, c=None, **kw):
func(arga=a, argb=b, **kw)
#do something with c
def func(arga=None, argb=None, argc=None):
....
Can I replicate part of the signature of func
, namely the missing args, without imitating every missing arg of func
manually?
Put it more simply, I want to see argc
in keywords of myfunc such that myfunc?
would be different. It would contain argc. myfunc(a=None,b=None,c=None,argc=None)
@functools.wraps
allows for wrapping a complete functions. Using partial
can subtract args. But don't know to add.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,虽然不是微不足道的 -
Python的内省功能允许您检查目标函数声明的所有参数,并且可以以编程方式构建一个新功能,该功能将自动包含这些属性。
I have written this for a project of mine, and had exposed the relevant code as my answer here:
我不会将其标记为重复,因为另一个问题更担心记录新功能。
如果您想尝试使用代码,也许使用更简单的内容,则可以检查
ixply.signature
从标准库中调用,这使人们可以发现有关参数和默认参数的所有内容目标功能。通过此信息构建新功能有点棘手,但可能会遇到 - 但始终可以诉诸
exec
调用,该调用可以从字符串模板中创建一个新功能。那里的答案遵循这一行。yes, it is possible, though not trivial -
Python's introspection capabilities allow you to check all parameters the target function declares, and it is possible to build a new function programmatically that will include those attributes automatically.
I have written this for a project of mine, and had exposed the relevant code as my answer here: Signature-changing decorator: properly documenting additional argument
I will not mark this as duplicate, since the other question is more worried about documenting the new function.
If you want to give a try, with your code, maybe with something simpler, you can check the
inspect.signature
call from the standard library, which allows one to discover everything about parameters and default arguments of the target function.Building a new function from this information is a bit more tricky, but possible - but one can always resort to a
exec
call which will can create a new function from a string template. The answer there follows this line.我不确定这里还要求什么,但是我在这里有
functools.partial
的替代代码可能会适用???(编辑>)
此处的区别与
部分
是mkcall
参数是字符串,而不是一系列参数。然后,可以根据需要在调用目标功能之前根据需要的任何适当要求对该字符串进行格式和分析。(<编辑)
I'm not sure what is being asked here either but I have here alternative code to
functools.partial
that might be adapted ???(edit>)
The difference here from
partial
is that themkcall
argument is a string rather than a series of arguments. This string can then be formatted and analysed according to whatever appropriate requirements are needed before the target function is called.(<edit)