[Python] Difference Between functools partial and a closure

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    I recently learned about functools.partial. I understand it is meant for currying functions. It seems to me its awfully similar to how I've used closures many times in Python. I often write closures to capture or fix some parameters in a function (as shown below). But I've read online that curried functions and closures are not the same thing. Given that, I am trying to understand where one might use partial instead of writing a closure using function or a lambda.

    Consider the simple example below. Here it seems they aren't much different.

    Can anyone provide a motivating example where partial is needed to solve a problem that a regular function or a lambda expression closure cannot?

    from functools import partial

    def func(a, b, c):
    return a * b + c

    funcC = partial(func, 1, 2)
    funcC_alt = lambda c: func(1, 2, c)

    funcC(5) # 7
    funcC_alt(5) # 7

    Continue reading...

Compartilhe esta Página