Skip to content

Instantly share code, notes, and snippets.

@pn11
Last active September 17, 2019 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pn11/bf7e0ebf80f8a7293e77cc1e58fe1c14 to your computer and use it in GitHub Desktop.
Save pn11/bf7e0ebf80f8a7293e77cc1e58fe1c14 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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