Wizard
Wizard

Reputation: 22083

Refactor partial function with lambda

In the official docs 10.2. functools about partial

Roughly equivalent to:

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

I try to understand the universal structure with synonymous function.

partial = lambda func, *args, **kwargs: func(*args, **kwargs)

Does my understanding make sense?

Upvotes: 0

Views: 59

Answers (1)

abarnert
abarnert

Reputation: 365707

You're missing two major things.


First, your version doesn't pass along the keyword arguments. To do that, you need to splat them as well:

lambda *args, **kwargs: func(*args, **kwargs)

But let's ignore that for the moment. The bigger problem is that you're missing the partial arguments, which is the entire point of partial. For example:

>>> def f(a, b):
...     return a + b
>>> add2 = partial(f, 2)
>>> add2(3)
5
>>> add2 = lambda *args: f(*args)
>>> add2(3)
f() missing 1 required positional argument: 'b'

To do the same thing, you'd need to do this:

>>> add2 = lambda *args: f(2, *args)
>>> add2(3)
5

… or, equivalently:

>>> add2 = lambda *args: f(*((2,) + args))
>>> add2(3)
5

Also, there's no good reason to use lambda here. The point of lambda is that (a) you don't have to come up with a name, and (b) you can use it in an expression. If you're just going to use it in an assignment statement to give it a name, better to use def:

def add2(*args): return f(*((2,) + args))

Upvotes: 2

Related Questions