PythonObjectOriented

From Traxel Wiki
Revision as of 04:38, 3 November 2023 by RobertBushman (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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=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)
  1. Usage:

data_manager = DataManager('data.json') print(data_manager.get_data_by_key('some_key')) </syntaxhighlight>