Skip to content

Instantly share code, notes, and snippets.

@nmariz
Created October 15, 2012 11:20
Show Gist options
  • Save nmariz/3892000 to your computer and use it in GitHub Desktop.
Save nmariz/3892000 to your computer and use it in GitHub Desktop.
Python Singleton Metaclass
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