Skip to content

Instantly share code, notes, and snippets.

@wmalarski
Created March 28, 2019 06:39
Show Gist options
  • Save wmalarski/001846e2cc995564398e7ef868bf8897 to your computer and use it in GitHub Desktop.
Save wmalarski/001846e2cc995564398e7ef868bf8897 to your computer and use it in GitHub Desktop.
from collections import defaultdict
class Context(object):
def __init__(self):
self._classes = {}
self._instances = {}
def feature(self, component_cls):
class Feature(object):
def __init__(self2, feature_cls):
self2._wrapped = feature_cls()
def __getattr__(self2, name):
return getattr(self2._wrapped, name)
class CallWrapper(object):
def __init__(self2, feature_cls):
self2._feature_cls = feature_cls
self._classes[component_cls].append(self2)
def __call__(self2):
return Feature(self2._feature_cls)
return CallWrapper
def component(self, cls):
class ComponentWrapper(object):
def __init__(self2, name, *args, **kwargs):
self2._wrapped = cls(*args, **kwargs)
self._instances[name] = {
feature_cls() for feature_cls in self._classes[ComponentWrapper]
}
def __getattr__(self2, name):
return getattr(self2._wrapped, name)
self._classes[ComponentWrapper] = []
return ComponentWrapper
context = Context()
@context.component
class MatComponent(object):
def __init__(self, *args, **kwargs):
self.x = 'component'
def f(self):
print('MatComponent1.f')
@context.feature(MatComponent)
class MatFeature1(object):
def __init__(self, *args, **kwargs):
self.x = 'feature'
def main():
mc1 = MatComponent('a')
print(type(mc1))
print(mc1.x)
mc1.f()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment