0

I want to provide a class, that contains a dictionary, that should be accessible all over my package. This class should be initialized by another class, which is a database connector.

From the database I retrieve the mapping but I want to do this only once on initialization of the database connector. Furthermore this mapping than should be availabe to all other modules in my package without getting the instance of the database connector passed through all function calls.

I thought about using a Singleton pattern and tried some stuff from this SO post. But I can't find a working solution.

I tried it this way with metaclass:

The mapping class:

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class CFMapping(metaclass=Singleton):

    def __init__(self, cf_mapping: dict):
        self._cf_mapping = cf_mapping

    @classmethod
    def get_cf_by_name(cls, name: str) -> str:
        return cls._cf_mapping.get(name)

The database connector

class DBConnector:
    def __init__(....):
        # some init logic, connection to db etc...
        self.cf_mapping = self.get_cf_mapping() # just returning a dict from a rest call

Now i expect the mapping to be accesible via the DBConnector instance. But at other scripts where I don't have this instance I would like to access the mapping just over a static/class method like this:

CFMapping.get_cf_by_name("someName")
# leads to AttributeError as CFMapping has no attribute _cf_mapping

Is there a way to get this construct to work the way I want it to or is there some better approach for some problem like this?

Igl3
  • 4,900
  • 5
  • 35
  • 69
  • The question is not clear. What is mapping? What do letters c & f mean? Where do you instantiate `CFMapping`? What is `get_cf_mapping` method? –  May 17 '19 at 06:48
  • Also I don't see any relation between `DBConnector` and `CFMapping`. You may replace line `return cls._cf_mapping.get(name)` with `return cls._instances.get(name)` and the construct gonna work. No idea if this way anyhow useful for the problem. Add more details please. –  May 17 '19 at 06:52

0 Answers0