PythonObjectOriented

From Traxel Wiki
Jump to navigation Jump to search

Singleton

import json
from threading import Lock

class SingletonMeta(type):
    _instances = {}
    _lock: Lock = Lock()
    
    def __call__(cls, *args, **kwargs):
        with cls._lock:
            if cls not in cls._instances:
                instance = super().__call__(*args, **kwargs)
                cls._instances[cls] = instance
            return cls._instances[cls]

class DataManager(metaclass=SingletonMeta):
    def __init__(self, filename):
        self.filename = filename
        self.data = None
        self.index = None
        self.load_data()

    def load_data(self):
        with open(self.filename, 'r') as file:
            self.data = json.load(file)
        self.index_data()

    def index_data(self):
        # Implement your indexing logic here.
        # For example, if your data is a list of dicts:
        self.index = {d['key']: d for d in self.data}

    def get_data_by_key(self, key):
        return self.index.get(key)

# Usage:
data_manager = DataManager('data.json')
print(data_manager.get_data_by_key('some_key'))