functools.partial [was Re: and on - topic and and off topic]

Matt Wheeler m at funkyhat.org
Fri Jul 29 04:18:50 EDT 2016


On Fri, 29 Jul 2016, 09:20 Steven D'Aprano, <steve at pearwood.info> wrote:

> I'm not sure that partial is intended as an optimization. It may end up
> saving time by avoiding evaluating arguments, but that's not why it exists.
> It exists to enable the functional programming idiom of partial evaluation
> in a simpler, more idiomatic (for functional programmers) way:
>
> function_of_one_argument = function_of_two_arguments(arg)
>
> rather than:
>
> def function_of_one_argument(x):
>     return function_of_two_arguments(arg, x)
>

I also find it useful for passing pre-argumented functions as callbacks or
similar, e.g. as finalizers in pytest or cleanup in Unit test. Those
mechanisms want a callable with no arguments:

`request.addfinalizer(functools.partial(cleanup(a, few, inputs)))`

And the partial is quite happy to execute later with no (new)  arguments.

(in general I prefer to use @pytest.yield_fixture but that doesn't always
fit)

>



More information about the Python-list mailing list