dict: retrieve the original key by key

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun May 15 06:18:45 EDT 2011


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.


-- 
Steven



More information about the Python-list mailing list