Skip to content

Instantly share code, notes, and snippets.

@gchiam
Last active February 9, 2017 03:01
Show Gist options
  • Save gchiam/d7f5e3fc4647502a69dfb8f20cdb58fb to your computer and use it in GitHub Desktop.
Save gchiam/d7f5e3fc4647502a69dfb8f20cdb58fb to your computer and use it in GitHub Desktop.
Singleton metaclass
class Singleton(type):
"""A singleton metaclass.
Usage:
class Foo(object):
__metaclass__ = Singleton
assert Foo() is Foo()
"""
def __init__(self, *args, **kwargs):
self.__instance = None
super(Singleton, self).__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super(Singleton, self).__call__(*args, **kwargs)
return self.__instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment