实现functools.partial,它附加了其他参数 [英] implementing functools.partial that prepends additional arguments
问题描述
functools.partial 的文档说它大致相当于":
The documentation for functools.partial says that it is "roughly equivalent to":
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords) # line to change
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
如果我想实现一个附加附加参数的版本, 看来我只需要更改指示的行即可.
If I wanted to implement a version that prepends the additional arguments, it seems like I'd just have to change the indicated line.
仅复制此代码,我是否还要担心其他功能/陷阱?
Are there any other features/gotchas that I should be worried about in just copying this code?
推荐答案
查看 _functoolsmodule.c
,我认为没有什么可担心的.
Looking at the source code for _functoolsmodule.c
, I don't think there's much to worry about.
partial
的模块实现处理酸洗和repr
,但是其他所有功能都像在文档中一样工作,因此大概在C中实现它的原因只是为了提高效率.还有一个事实,它是类型,而不仅仅是函数闭包.
The module implementation of partial
handles pickling and repr
, but everything else looks like it works as in the documentation so presumably the reason it is implemented in C is just for efficiency. There is also the fact that it is a type rather than just being a function closure.
但是,请注意,在文档示例func
,args
和keywords
中,这些纯属修饰;也就是说,它们不能像实际的functools.partial
实例那样被覆盖.一种替代方法是子类functools.partial
:
Note, however, that in the documentation example func
, args
, and keywords
are purely cosmetic; i.e. they are not overridable as they are with actual functools.partial
instances. One alternative would be to subclass functools.partial
:
class rpartial(partial):
def __call__(self, *args, **kwargs):
kw = self.keywords.copy()
kw.update(kwargs)
return self.func(*(args + self.args), **kw)
这篇关于实现functools.partial,它附加了其他参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!