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))
# 2 - bug

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

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

# partial

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

fpc = [partial(f, i) for i in range(3)]
# 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.

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

Python-ideas mailing list
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to