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
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