Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- from inspect import isfunction
- class SchemaBase:
- def __init__(self, *args, **kwargs):
- print('calling base init')
- self._extras = {}
- for name, value in kwargs.items():
- if name in self.__fields__:
- setattr(self, name, value if value else None)
- else:
- self._extras[name] = value
- # I can't figure out a better way to do this, sigh!
- for name, value in self.__fields__.items():
- if not hasattr(self, name):
- setattr(self, name, value)
- class SchemaMeta(type):
- def __new__(self, name, bases, attrs):
- klass_attrs = {}
- fields = {}
- for name, attr in attrs.items():
- if not isfunction(attr) and not name.startswith('_'):
- # we ignore class setup for now
- # TODO: replace with fields
- fields[name] = None
- else:
- klass_attrs[name] = attr
- if klass_attrs.get('__init__'):
- klass_attrs['__init__'] = \
- auto_super_caller(klass_attrs.get('__init__'))
- klass = super().__new__(self, name, bases, klass_attrs)
- klass.__fields__ = fields
- return klass
- def auto_super_caller(class_init):
- orig_init = class_init
- def init_wrapper(self, *args, **kwargs):
- super(self.__class__, self).__init__(*args, **kwargs)
- if orig_init:
- orig_init(self, *args, **kwargs)
- return init_wrapper
- def schema(cls):
- attrs = cls.__dict__.copy()
- attrs.pop('__dict__', None)
- attrs.pop('__weakref__', None)
- if hasattr(cls, '__qualname__'):
- attrs['__qualname__'] = cls.__qualname__
- bases = tuple([SchemaBase] + list(cls.__bases__))
- return SchemaMeta(cls.__name__, bases, attrs)
- class A:
- def __init__(self, *args, **kwargs):
- print('calling A init')
- def foo(self):
- pass
- class B:
- def __init__(self, *args, **kwargs):
- print('calling B init')
- def baz(self):
- pass
- @schema
- class T(A, B):
- a = 1
- b = 2
- c = 3
- def __init__(self, *args, **kwargs):
- print('calling T init')
- #super().__init__(*args, **kwargs)
- def bar(self):
- pass
- a = T(a=10, b=11, x=1)
- b = T(a=20, c=22, y=2)
- c = T(b=31, c=32)
- print(dir(T))
- print(dir(a))
- print(dir(b))
- print(dir(c))
- print(id(a), id(b), id(c))
- print(T, a.a, b.a, c.a)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement