UniqueObject pattern

Chris feb04.20.netman at spamgourmet.com
Thu Feb 19 21:05:01 CET 2004


I have an application that creates a lot of objects that are initialized by
parsing a string.  In many cases, the initalization strings are duplicated
many times, which results in a lot of duplicate objects being created at
runtime.  I originally utilized a factory to generate new object instances,
but it was a pain to write a new factory for each object tpye.  So I created
a class called UniqueObject, and subclassed all my objects with it.

import weakref

class UniqueObject(object):
    __instances = weakref.WeakValueDictionary()
    def __new__(cls, source):
        return cls.__instances.setdefault(source,
                            super(UniqueObject, cls).__new__(cls, source))

    def getSource(self):
        return self.__class__.__instances.keys()[
            self.__class__.__instances.values().index(self)]

This insured that duplicate strings would not result in the creation of
duplicate objects, and I could us "is" for comparisons instead of having to
define an "__eq__".

>>> class X(UniqueObject):
    def __init__(self, source):
        pass

>>> x1, x2, x3, x4 = X('spam'), X('spam'), X('eggs'), X('spam')
>>> x1 is x2
True
>>> x2 is x3
False
>>> x1 != x3
True
>>> x3 is not x4
True
>>> x1 in (x4,)
True
>>> x1.getSource()
'spam'

Am I reinventing the wheel here?  Is there a way to accomplish the same
thing in a built-in, or more Pythonic way?

Chris





More information about the Python-list mailing list