Here's my code which I use to create "cached" instances:
class Foo(object):
_instances = {}
def __new__(cls, index):
if index in cls._instances:
return cls._instances[index]
instance = super().__new__(cls)
cls._instances[index] = instance
return instance
def __init__(self, index):
print('__init__: {0}'.format(index))
The problem appears when I already have an instance of the same index; it should do nothing except return the existing instance, but it also invokes __init__
on the new instance:
>>> f = Foo(1)
__init__: 1
>>> f.x = True
>>> b = Foo(1)
__init__: 1
>>> b.x
True
The problem is b = Foo(1)
also prints __init__: 1
when it "shouldn't" (I don't want it to).
Is there a way to prevent the__init__
from being called in such cases?