[Python-ideas] Make partial a built-in

Terry Reedy tjreedy at udel.edu
Tue Sep 20 17:03:27 EDT 2016


On 9/20/2016 11:51 AM, Guido van Rossum wrote:
>
> We seem to have fundamentally different ideas of what sort of code is
> most readable. The alternative to partial is usually a lambda,

Partial and lambda are different in that partial captures variable 
values immediately, whereas lambda does not, unless the default argument 
trick, with its attendant disadvantages, is used.  I consider this one 
reason to chose one or the other.  (The greater flexibility of lambda, 
pointed out by David Mertz, is another.)

# Demonstration
from functools import partial

def f(a): print(a)

# lambda

fl = []
for i in range(3):
     fl.append(lambda: f(i))
fl[0]()
# 2 - bug

flc = [lambda: f(i) for i in range(3)]
flc[0]()
# 2 - bug

flcd = [lambda i=i: f(i) for i in range(3)]
flcd[0]()
# 0 - correct

# partial

fp = []
for i in range(3):
     fp.append(partial(f, i))
fp[0]()
# 0 - correct

fpc = [partial(f, i) for i in range(3)]
fpc[0]()
# 0 - correct

> and the
> signature of the lambda helps me understand how it is being called.

The 'i=i' signature is typically left out by beginners creating multiple 
functions in a loop, leading to one of *the* most frequent of FAQs.
https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result

When added 'i=i', better written '_i=i', is misleading, as '_i' is not 
really a parameter and 'i' is not a replaceable default value, but is 
supposed to be a fixed value, as with partial.

I believe in a previous thread about creating functions in a loop, it 
was generally agreed that using partial is better.  (This alternative 
has not made it to the FAQ yet, but I thing it should.)

I otherwise generally agree with what you wrote.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list