Skip to content

Instantly share code, notes, and snippets.

@jirihnidek
Last active February 3, 2020 18:01
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 jirihnidek/73676d71186adac40afcbdfb2c7bdcb2 to your computer and use it in GitHub Desktop.
Save jirihnidek/73676d71186adac40afcbdfb2c7bdcb2 to your computer and use it in GitHub Desktop.
Python singleton
class Singleton(object):
"""
Singleton and parent for singletons
"""
_instance = None
_initialized = False
def __new__(cls, *args, **kwargs):
"""
Function called, when new instance of Identity is requested
"""
if isinstance(cls._instance, cls):
print("Instance of %s already exists" % cls.__name__)
cls.__init__ = lambda *args, **kwargs: None
else:
print("Creating new instance of %s" % cls.__name__)
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
class InitializingSingleton(object):
"""
Singleton and parent for singletons initializing instance everytime
InitializingSingleton() is called. We will probably not need it.
"""
_instance = None
_initialized = False
def __new__(cls, *args, **kwargs):
"""
Function called, when new instance of Identity is requested
"""
if isinstance(cls._instance, cls):
print("Instance of %s already exists" % cls.__name__)
else:
print("Creating new instance of %s" % cls.__name__)
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
class Identity(Singleton):
"""
Example of singleton (__init__ initialize only once)
"""
def __init__(self, foo):
print('Initializing %s' % self.__class__.__name__)
self.foo = foo
def __str__(self):
return '%s, %s' % (id(self), self.foo)
class CertSorter(Singleton):
"""
Another example of singleton (__init__ doesn't do anything)
"""
def __init__(self):
print('Initializing %s' % self.__class__.__name__)
def __str__(self):
return '%s' % id(self)
class ProfileManager(InitializingSingleton):
"""
Last example of singleton (__init__ initialize everytime)
"""
def __init__(self, foo):
print('Initializing %s' % self.__class__.__name__)
self.foo = foo
def __str__(self):
return '%s, %s' % (id(self), self.foo)
def main():
"""
Example with singleton
"""
ident_01 = Identity(foo="foo")
print(ident_01)
ident_02 = Identity(foo="bar")
print(ident_02)
ident_03 = Identity(foo="bar")
print(ident_03)
cs_01 = CertSorter()
print(cs_01)
cs_02 = CertSorter()
print(cs_02)
pm_01 = ProfileManager(foo="foo")
print(pm_01)
pm_02 = ProfileManager(foo="bar")
print(pm_02)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment