Skip to content

Instantly share code, notes, and snippets.

@kovalbogdan95
Last active October 29, 2019 14:20
Show Gist options
  • Save kovalbogdan95/1e2b3b7015711d034882112f73f37f27 to your computer and use it in GitHub Desktop.
Save kovalbogdan95/1e2b3b7015711d034882112f73f37f27 to your computer and use it in GitHub Desktop.
Singletone examples in python
# One
class Singleton:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
a = Singleton()
a.prop = "PROP"
print(a.prop)
b = Singleton()
print(b.prop)
b.prop = "NEW"
print(a.prop)
assert a is b
# Two
class BorgSingleton:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
c = BorgSingleton()
c.prop = "PROP"
print(c.prop)
d = BorgSingleton()
print(d.prop)
d.prop = "NEW"
print(c.prop)
assert a is b
# Three
class SingletonMetaclass(type):
instance = None
def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(SingletonMetaclass, cls).__call__(*args, **kwargs)
return cls.instance
class MSingleton(metaclass=SingletonMetaclass):
pass
a = MSingleton()
a.prop = "PROP"
print(a.prop)
b = MSingleton()
print(b.prop)
b.prop = "NEW"
print(a.prop)
assert a is b
# Four
class AdHookSingleton:
__instance = None
@classmethod
def getInstance(cls):
if not cls.__instance:
cls.__instance = AdHookSingleton()
return cls.__instance
a = AdHookSingleton().getInstance()
a.prop = "PROP"
print(a.prop)
b = AdHookSingleton().getInstance()
print(b.prop)
b.prop = "NEW"
print(a.prop)
assert a is b
# Five
# You can create a module (modules are singletone by default in Python)
# https://hub.packtpub.com/python-design-patterns-depth-singleton-pattern/
# https://www.oreilly.com/library/view/python-cookbook/0596001673/ch05s23.html
# https://gist.github.com/nmariz/3892000
# https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
# https://webdevblog.ru/realizaciya-shablona-singleton-v-python/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment