Why is lambda allowed as a key in a dict?
Duncan Booth
duncan.booth at invalid.invalid
Tue Mar 10 10:06:38 EDT 2009
Iain King <iainking at gmail.com> wrote:
> Sort of tangenitally; is there any real difference between the outcome
> of the two following pieces of code?
>
> a = lambda x: x+2
>
> def a(x):
> return x+2
>
Disassemble it to see. The functions themselves have identical code
bytes, the only difference is the name of the code objects (and that
carries through to a difference in the function names).
>>> def f():
a = lambda x: x+2
def b(x):
return x+2
dis(a)
dis(b)
>>> from dis import dis
>>> dis(f)
2 0 LOAD_CONST 1 (<code object <lambda> at
0119FDA0, file "<pyshell#10>", line 2>)
3 MAKE_FUNCTION 0
6 STORE_FAST 0 (a)
3 9 LOAD_CONST 2 (<code object b at 0119FDE8,
file "<pyshell#10>", line 3>)
12 MAKE_FUNCTION 0
15 STORE_FAST 1 (b)
5 18 LOAD_GLOBAL 0 (dis)
21 LOAD_FAST 0 (a)
24 CALL_FUNCTION 1
27 POP_TOP
6 28 LOAD_GLOBAL 0 (dis)
31 LOAD_FAST 1 (b)
34 CALL_FUNCTION 1
37 POP_TOP
38 LOAD_CONST 0 (None)
41 RETURN_VALUE
>>> f()
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 0 (2)
6 BINARY_ADD
7 RETURN_VALUE
4 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (2)
6 BINARY_ADD
7 RETURN_VALUE
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list