PythonObjectOriented: Difference between revisions

From Traxel Wiki
Jump to navigation Jump to search
(Created page with "Category:Python = Singleton = </syntaxhighlight lang="python" lines> 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=Sin...")
 
Line 1: Line 1:
[[Category:Python]]
[[Category:Python]]
= Singleton =
= Singleton =
</syntaxhighlight lang="python" lines>
<syntaxhighlight lang="python" lines>
import json
import json
from threading import Lock
from threading import Lock

Revision as of 04:38, 3 November 2023

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'))