Skip to content

Instantly share code, notes, and snippets.

@Nurdok
Created July 14, 2012 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nurdok/3111781 to your computer and use it in GitHub Desktop.
Save Nurdok/3111781 to your computer and use it in GitHub Desktop.
Singleton Blog Post
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
class MySingleton(object):
INSTANCE = None
def __init__(self):
if self.INSTANCE is not None:
raise ValueError("An instantiation already exists!")
# do your init stuff
@classmethod
def get_instance(cls):
if cls.INSTANCE is None:
cls.INSTANCE = MySingleton()
return cls.INSTANCE
class MySingleton:
""" A python singleton """
class __impl:
""" Implementation of the singleton interface """
# implement your stuff in here
pass
# storage for the instance reference
__instance = None
def __init__(self):
""" Create singleton instance """
# Check whether we already have an instance
if MySingleton.__instance is None:
# Create and remember instance
MySingleton.__instance = MySingleton.__impl()
# Store instance reference as the only member in the handle
self.__dict__['_Singleton__instance'] = MySingleton.__instance
def __getattr__(self, attr):
""" Delegate access to implementation """
return getattr(self.__instance, attr)
def __setattr__(self, attr, value):
""" Delegate access to implementation """
return setattr(self.__instance, attr, value)
enum MySingleton {
INSTANCE;
// methods, members, etc.
}
class SingletonType(type):
def __call__(cls, *args, **kwargs):
try:
return cls.__instance
except AttributeError:
cls.__instance = super(SingletonType, cls).__call__(*args, **kwargs)
return cls.__instance
class MySingleton(object):
__metaclass__ = SingletonType
# ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment