Skip to content

Instantly share code, notes, and snippets.

@DirkHoffmann
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save DirkHoffmann/b182f2ec237f366b8f9b to your computer and use it in GitHub Desktop.

Select an option

Save DirkHoffmann/b182f2ec237f366b8f9b to your computer and use it in GitHub Desktop.
Decorator for making a class a singleton (without becoming a method)
class Singleton(type):
"""
Comme discuté sur la liste python@services.cnrs.fr (accès restreint à la communauté ESR)
https://listes.services.cnrs.fr/wws/arc/python/2015-04/msg00006.html
- Solution pour singleton co(?)-production Loïc Gouarin, Konrad Hinsen et al.
"""
_instances = {}
def __call__(self, *args, **kwargs):
key = (str(self), args, str(kwargs))
if key not in self._instances:
self._instances[key] = super(Singleton, self).__call__(*args, **kwargs)
self._instances
return self._instances[key]
class A:
"""
ma classe A
"""
__metaclass__ = Singleton
def __init__(self, x):
self.x = x
class B(A):
def __init__(self, x):
super(B, self).__init__(x)
if __name__ == '__main__':
a = A(1)
b = A(1)
c = A(2)
d = B(1)
print a is b
print a is c
print a is d
import inspect
print inspect.isclass(A)
print inspect.isfunction(A)
print inspect.isclass(B)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment