Why is lambda allowed as a key in a dict?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Mar 10 20:08:07 EDT 2009


En Tue, 10 Mar 2009 21:23:54 -0200, Craig Allen <callen314 at gmail.com>  
escribió:

>
>> I think the point is that function objects compare by object identity,
>> so the two lambdas you use above are not equal even though they have the
>> same code.
>
> it raises an interesting question about why doesn't it.  I can think
> of practical answers to that, obviously, but in principle, if a
> function compiles to exactly the same byte code, you obviously do not
> need two copies of it, and like strings shouldn't an identical
> function have the same id?

A function is (code + its environment); this includes globals, closures,  
and its default argument values. So having the same code object doesn't  
mean it's the same function:

py> def f(x):
...   def g():
...     return x
...   return g
...
py> x1 = f(10)
py> x2 = f(20)
py> x3 = f(30)
py> x1(), x1, x1.func_code
(10,
  <function g at 0x00C2A170>,
  <code object g at 00B93D10, file "<stdin>", line 2>)
py> x2(), x2, x2.func_code
(20,
  <function g at 0x00C233B0>,
  <code object g at 00B93D10, file "<stdin>", line 2>)
py> x3(), x3, x3.func_code
(30,
  <function g at 0x00C1ADB0>,
  <code object g at 00B93D10, file "<stdin>", line 2>)
py> x1.func_code is x2.func_code is x3.func_code
True

Note that the returned "g" function is a different function each time, but  
g.func_code is always the same code object.

> This is merely philosophical, I don't see the value in making this so
> (a slight optimizaton and perhaps better conformity to other python
> features), but I do think it's an interesting question.

Making == detect "equivalent" functions would slow down all function  
comparisons (as I posted earlier) and I don't see any advantage...

-- 
Gabriel Genellina




More information about the Python-list mailing list