Last active
April 1, 2018 05:47
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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