Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Why are multiple objects created in below implementation?

Below is a very simple code where I was trying to implement a very basic ordered in-app cache. I was expecting that, in each call on services.cache, I will get the same id throughout app lifetime. But the value differs. What is the reason behind this?

What I understand is that, self.__cache should reuse the first InAppCache object it creates. What I am missing here?

from collections import OrderedDict
import sys


class InAppCache(OrderedDict):
    MAX_MEMORY = 50 * 10 ** 6

    def add(self, key, value):
        self[key] = value

    def remove(self, key):
        return self.popitem(last=False)

    def is_remove_needed(self):
        return sys.getsizeof(self) > self.MAX_MEMORY

    def reset(self):
        self.clear()


class Services:

    def __init__(self):
        self.__cache = None

    @property
    def cache(self):
        if not self.__cache:
            self.__cache = InAppCache()
        print(id(self.__cache))
        return self.__cache


services = Services()
services.cache
services.cache
services.cache
services.cache
services.cache
services.cache

Upvotes: 0

Views: 43

Answers (2)

blue note
blue note

Reputation: 29089

Because the bool(ordered_dict) is False. Use self.__cache is None instead.

Upvotes: 0

deceze
deceze

Reputation: 522372

An OrderedDict, which is a subclass of dict, is considered falsey if empty. So your if not self.__cache test is always true until you put something into the dict. Use if self.__cache is None instead.

Upvotes: 2

Related Questions