dict: retrieve the original key by key

Christoph Groth cwg at falma.de
Sun May 15 06:46:15 EDT 2011


Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:

> On Sun, 15 May 2011 11:11:41 +0200, Christoph Groth wrote:
>
>> I would like to avoid having _multiple_ objects which are equal (a ==
>> b) but not the same (a is not b).  This would save a lot of memory.
>
> Based on the idea of interning, which is used for Python strings:
>
> cache = {} def my_intern(obj):
>     return cache.setdefault(obj, obj)
>
>
> x = make_some_object() x = my_intern(x)
>
> This ensures that equal objects in the graph are not just equal, but
> the same cached object.

This requires another dictionary, though.

But hey, they keys of my dictionary are actually strings, so I can use
the built-in intern.  Somehow, I have never stumbled accross this
built-in function so far.

Thanks a lot for the hint!

Christoph




More information about the Python-list mailing list