How to create simple thread safe singletone that protect __init__ on import module - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: How to create simple thread safe singletone that protect __init__ on import module (/thread-25933.html) |
How to create simple thread safe singletone that protect __init__ on import module - umen - Apr-16-2020 Hello all i trying to create simple singletone that is easy to understand . i need it to be thread safe , and that the __init(self)__ should be initiated only once even if it importing the singletune module . i managed to construct this : class DBUtils(): __instance = None __data = None def __new__(cls): if cls.__instance is None: cls.__instance = super(DBUtils, cls).__new__(cls) cls.__instance.__initialized = False return cls.__instance def __init__(self): if (self.__initialized): return self.__initialized = True self.__data = 1but im not sure if it thread safe .. my question is : are there any more elegant way to implemant it ? to be able using metadata or inheritance of somekind ? examples from the internet dosn't protecting from invoking the __init(self)__ from import module stage . Thanks |