Python Forum
How to create simple thread safe singletone that protect __init__ on import module
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create simple thread safe singletone that protect __init__ on import module
#1
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 = 1
but 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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Import Python file with a name of a module in Stantard Library tiago_code 7 3,137 Dec-11-2019, 06:08 AM
Last Post: ICanIBB
  Math Module import Jack_Sparrow 3 6,438 Apr-30-2018, 01:41 PM
Last Post: snippsat
  [URGENT] Trying to create a simple password manager in python equanox314 5 11,229 Jul-28-2017, 08:04 AM
Last Post: DeaD_EyE
  Need To Create Simple Mutiple Choice Quiz In Tkinter Rashi 5 15,537 Apr-01-2017, 04:03 AM
Last Post: Rashi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020