Last active
February 9, 2017 03:01
-
-
Save gchiam/d7f5e3fc4647502a69dfb8f20cdb58fb to your computer and use it in GitHub Desktop.
Singleton metaclass
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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