[Python-Dev] PEP 8 modernisation

Terry Reedy tjreedy at udel.edu
Thu Aug 1 22:56:55 CEST 2013


On 8/1/2013 11:35 AM, Alexander Belopolsky wrote:

> Here is one use-case where .. =  lambda .. cannot be replaced with def ..
>
> op['add'] = lambda x,y: x+y
> op['mul'] = lambda x, y: x*y

Yes, you are binding the functions to named slots, not to names, so not 
covered by the PEP. Once might still want to replace the expressions 
themselves, at the cost of more typing, for the advantage of better 
representations.

op = { 'add': lambda x,y: x*y, 'mul':  lambda x, y: x+y}
print(op)  # no apparent problem
# {'add': <function <lambda> at 0x000000000227F730>,
# 'mul': <function <lambda> at 0x00000000033867B8>}

def add(x, y): return x + y
def mul(x, y): return x * y
# These can be unittested individually

op = {'add': mul, 'mul': add}  # mistake easily seen in original code
print(op)
# {'add': <function mul at 0x0000000003440950>,
# 'mul': <function add at 0x00000000034408C8>}
# problem apparent to user who import this object and prints it when 
code fails

If op has 20 such functions, names become even more of an advantage

-- 
Terry Jan Reedy



More information about the Python-Dev mailing list