UniqueObject pattern

C

Chris

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__".
def __init__(self, source):
pass
'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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,966
Members
47,515
Latest member
Harvey7327

Latest Threads

Top