Skip to content

Instantly share code, notes, and snippets.

@mahmoudajawad
Last active April 1, 2018 05:47
Show Gist options
  • Save mahmoudajawad/01b660cd79754574c1bcffb8a6a8a51a to your computer and use it in GitHub Desktop.
Save mahmoudajawad/01b660cd79754574c1bcffb8a6a8a51a to your computer and use it in GitHub Desktop.
Python (3.x) singleton metaclass. It allows manipulation of child classes, as well as converting all class funcs to classmethod's.
class ClassSingleton(type):
def __new__(cls, cls_name, bases, attrs):
for name, attr in attrs.items():
if callable(attr):
attrs[name] = classmethod(attr)
return type.__new__(cls, cls_name, bases, attrs)
def __init__(cls, cls_name, bases, attrs):
cls.singleton()
from class_singleton import ClassSingleton
class BaseClass(metaclass=ClassSingleton):
attrs = {}
def singleton(self):
for attr in self.attrs.keys():
#do some magic to attrs
pass
class MyClass(BaseClass):
attrs = {'some':'meaningful', 'attrs':'here'}
def non_class_method(self, *args, **kwargs):
#metaclass ClassSingleton would decorate this function (and all other funcs in this class) as classmethod.
return {'attrs':self.attrs, 'args':args, 'kwargs':kwargs}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment