Skip to content

Instantly share code, notes, and snippets.

@pn11
Last active Sep 17, 2019
Embed
What would you like to do?
Singleton in Python3
import threading
class ThreadingSingleton:
_instance = None
_lock = threading.Lock()
def __init__(self):
print('__init__')
def __new__(cls):
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.init()
return cls._instance
def init(self):
self.test = False
print('init')
if __name__ == "__main__":
t1 = ThreadingSingleton()
t2 = ThreadingSingleton()
print(t1.test)
print(t2)
print(t1)
@pn11

This comment has been minimized.

Copy link
Owner Author

@pn11 pn11 commented Sep 17, 2019

Output

init
__init__
__init__
False
<main.ThreadingSingleton object at 0x7f52ccec9f98>
<main.ThreadingSingleton object at 0x7f52ccec9f98>

init called only once though __init__ called twice. So members of the class must be initialized in init, not __init__.
The last two lines of output shows t1 and t2 are the same instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment