Skip to content

Instantly share code, notes, and snippets.

@SAW4
Last active June 18, 2017 17:59
Show Gist options
  • Save SAW4/b0075884f981eddd69cd93125166b6ff to your computer and use it in GitHub Desktop.
Save SAW4/b0075884f981eddd69cd93125166b6ff to your computer and use it in GitHub Desktop.
Understanding metaclass and Singleton in Python

How to use metaclass to implement Singleton in Python

First, you need to know that instance of metaclass is class,
just like : an instance of class is object, they have similar idea

Then you need to change the rule of metaclass of your class, to let it only allow create the instance once only.
If the class instance is not None (instance is existed), then return the instance, else create new instance of class.

One more important thing, metaclass is type
class is the instance of type (metaclass)
the origin of class is type (I may say that)
python use type to instantiate a new class

Here is some useful reference:
https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python

class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls._instance = None
def __call__(cls, *args, **kw):
if cls._instance is None:
cls._instance = super(Singleton, cls).__call__(*args, **kw)
return cls._instance
class LempConfHelper(object):
__metaclass__ = Singleton
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment