Why is lambda allowed as a key in a dict?
"Martin v. Löwis"
martin at v.loewis.de
Tue Mar 10 19:54:39 EDT 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
True
So they do have the same byte code, namely:
py> dis.dis(a)
2 0 LOAD_CONST 1
3 LOAD_FAST 0
6 BINARY_MULTIPLY
7 RETURN_VALUE
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
== b.func_code.co_consts
False
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.
Regards,
Martin
More information about the Python-list
mailing list