Skip to content

Instantly share code, notes, and snippets.

@ftorto
Created February 21, 2017 20:16
Show Gist options
  • Save ftorto/806fb2ffb60a8fd3e77a44068f7ea325 to your computer and use it in GitHub Desktop.
Save ftorto/806fb2ffb60a8fd3e77a44068f7ea325 to your computer and use it in GitHub Desktop.
Singleton 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]
#Python2
class MyClass(BaseClass):
__metaclass__ = Singleton
#Python3
class MyClass(BaseClass, metaclass=Singleton):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment