Why is lambda allowed as a key in a dict?
"Martin v. Löwis"
martin at v.loewis.de
Wed Mar 11 00:54:39 CET 2009
> 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?
Having the same code is certainly not sufficient for the functions
to compare the same:
py> def a(x):
... return 3*x
py> def b(x):
... return 4*x
py> a.func_code.co_code == b.func_code.co_code
So they do have the same byte code, namely:
2 0 LOAD_CONST 1
3 LOAD_FAST 0
The difference is what constant 1 means: 3 in one case, and
4 in the other. So they should have the constants also to
compare the same, right? Those above don't:
py> a.func_code.co_code == b.func_code.co_code and a.func_code.co_consts
Now, you could also ask that many other code attributes should
be the same, such as co_argcount, co_stacksize, co_varnames, ...
If you ask that *all* code attributes are the same, you find a good
reason why the code objects shouldn't compare the same: they might
have different values for co_filename, or, if those are the same,
different values for co_firstlineno.
More information about the Python-list