I liked JW’s class pooling example at DevLog.nl. Below a rewrite without the global ClassPool and ’static’ ClassPool.id. Also EAFP in action:
class PooledClass(object):
'Pools instances by id'
_pool = {}
def __new__(cls, id):
"""Creator """
try:
return cls._pool[id]
except KeyError:
obj = object.__new__(cls)
cls._pool[id] = obj
return obj
def __init__(self, id):
'Constructor '
self.id = id
2006-10-09: Changed ’self’ to ‘cls’ in __new__