Created
October 15, 2012 11:20
-
-
Save nmariz/3892000 to your computer and use it in GitHub Desktop.
Python 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): | |
instance = None | |
def __call__(cls, *args, **kwargs): | |
if cls.instance is None: | |
cls.instance = super(Singleton, cls).__call__(*args, **kwargs) | |
return cls.instance | |
if __name__ == '__main__': | |
class Foo(object): | |
__metaclass__ = Singleton | |
a = Foo() | |
b = Foo() | |
assert a is b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment