A functools.partial implementation that adds extra arguments

The documentation for functools.partial says it is "roughly equivalent":

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 adds additional arguments, it seems I just need to change the specified string.

Are there any other / gotchas features that I should worry about when simply copying this code?

+8
python functools
source share
2 answers

Looking at the source code of _functoolsmodule.c , I don't think there is anything to worry about.

The partial module implementation handles etching and repr , but everything else looks like it works as in the documentation, so the reason why it is implemented in C seems to be just efficiency. There is also the fact that this is a type, not just a function closure.

Note, however, that in the sample documentation, func , args and keywords are purely cosmetic; they are not excessive, as in real instances of functools.partial . One alternative would be a subclass of functools.partial :

 class rpartial(partial): def __call__(self, *args, **kwargs): kw = self.keywords.copy() kw.update(kwargs) return self.func(*(args + self.args), **kwargs) 
+6
source share

One mistake is how your private assignment would handle arbitrary arguments, for example, in the following example:

 def f(a,b, *args): pass 

Now partially apply f to arguments 1 and 2:

 g = partial(f, 1, 2) 

What is the value of the parameter b in g ? Is it 1, or is it still expecting a value? In this regard, what is the meaning of a ? In other words, how many, if any, arguments that should be provided should be considered as additional arguments.

0
source share

All Articles