Why is lambda allowed as a key in a dict?

Terry Reedy tjreedy at udel.edu
Wed Mar 11 17:32:07 EDT 2009


r wrote:
> On Mar 11, 3:40 pm, Craig Allen <callen... at gmail.com> wrote:
>> On Mar 10, 1:39 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:

>>> Identical strings don't necessarily have the same id:

A more verbose way to put this is "Requesting a string with a value that 
  is the same an an existing string does not necessarily result in reuse 
of the existing string but mey result in creation of a new, duplicate 
string.

>>>     >>> a = "a"*1000
>>>     >>> b = "a"*1000
>>>     >>> id(a),id(b)
>>>     (137143648, 137144680)
>>>     >>> a==b
>>>     True

>> interesting, I thought they were supposed to.

Reuse of immutable objects is entirely up to the implementation. 
CPython reuses small ints and identifier-like strings that it 'expects' 
    would otherwise be duplicated.  There is no reason to expect that 
the programmer will ask for 'a'*1000 again instead of explicitly reusing 
the existing object.  On the other hand, identifiers are almost always 
reused, often multiple times..  (Non-reuse may even by a bug!.)

> Are you joking? two objects == two ids. if not i would dump Python
> forever!

Me too, but see rewording.

> Do you think Vector(0,0,0) and Vector(0,0,0) would have the same id?

If the instances of Vector are immutable, possibly yes.
If Vector(0,0,0) were typically called hundreds of times within a 
program, it might be worthwhile for the Vector class to pre-allocate one 
instance with that value and return it for each of the hundreds of 
calls.  That would be an implementation decision, which could be changed 
with experience.

Similarly, if one is populating a LARGE structure with duplicate values, 
it may be worthwhile to cache values that are not cached by the interpreter.

Terry Jan Reedy




More information about the Python-list mailing list