-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsingleton.py
25 lines (22 loc) · 1.09 KB
/
singleton.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from threading import Lock
# ala https://en.wikipedia.org/wiki/Singleton_pattern#Python_implementation
# and https://stackoverflow.com/questions/51896862/how-to-create-singleton-class-with-arguments-in-python
class Singleton (type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# Based on tornado.ioloop.IOLoop.instance() approach.
# See https://github.com/facebook/tornado
# Whole idea for this metaclass is taken from: https://stackoverflow.com/a/6798042/2402281
class ThreadSafeSingleton(type):
_instances = {}
_singleton_lock = Lock()
def __call__(cls, *args, **kwargs):
# double-checked locking pattern (https://en.wikipedia.org/wiki/Double-checked_locking)
if cls not in cls._instances:
with cls._singleton_lock:
if cls not in cls._instances:
cls._instances[cls] = super(ThreadSafeSingleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]