By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,627 Members | 1,211 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,627 IT Pros & Developers. It's quick & easy.

UniqueObject pattern

P: n/a
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
Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.