Skip to content Skip to sidebar Skip to footer

Memoized Objects Still Have Their __init__() Invoked?

So I am creating a memoized class, and have been observing a strange behavior. Here's the snippet of the code: class SomeClass(object): _Memoized = {} def __new__(cls, id

Solution 1:

The purpose of __new__ is to create a new instance, which is why Python calls __init__ on it. You might instead override __call__ on a metaclass to avoid creating a new instance.

class MemoMeta(type):
    def __init__(self, name, bases, namespace):
        super().__init__(name, bases, namespace)
        self.cache = {}
    def __call__(self, id_, *args, **kwargs):
        if id_ not in self.cache:
            print('New Instance')
            self.cache[id_] = super().__call__(id_, *args, **kwargs)
        else:
            print('Existing Instance')
        return self.cache[id_]

class SomeClass(metaclass=MemoMeta):
    def __init__(self, id_, *args, **kwargs):
        print('Running init')
        self.id = id_


def test():
    w1 = SomeClass(id_='w1')
    wx = SomeClass(id_='w1')
    print(id(w1), id(wx), id(w1) == id(wx))

test()

Post a Comment for "Memoized Objects Still Have Their __init__() Invoked?"