|
| 1 | +# Copyright 2017 CodiLime |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# Borrowed from the Veles project (https://github.com/codilime/veles/). |
| 16 | + |
| 17 | +import sys |
| 18 | +import types |
| 19 | +from collections import OrderedDict |
| 20 | + |
| 21 | + |
| 22 | +if sys.version_info < (3, 6): |
| 23 | + class NewType(type): |
| 24 | + def __init__(self, name, bases, ns, **kwargs): |
| 25 | + super(NewType, self).__init__(name, bases, ns) |
| 26 | + |
| 27 | + def __new__(cls, *args, **kwargs): |
| 28 | + if len(args) != 3: |
| 29 | + return super(NewType, cls).__new__(cls, *args) |
| 30 | + |
| 31 | + name, bases, ns = args |
| 32 | + |
| 33 | + init = ns.get('__init_subclass__') |
| 34 | + if isinstance(init, types.FunctionType): |
| 35 | + ns['__init_subclass__'] = classmethod(init) |
| 36 | + |
| 37 | + ns['_order'] = list(ns) |
| 38 | + |
| 39 | + self = super(NewType, cls).__new__(cls, name, bases, ns) |
| 40 | + |
| 41 | + for k, v in self.__dict__.items(): |
| 42 | + func = getattr(v, '__set_name__', None) |
| 43 | + if func is not None: |
| 44 | + func(self, k) |
| 45 | + |
| 46 | + init = getattr(super(self, self), '__init_subclass__', None) |
| 47 | + if init is not None: |
| 48 | + init(**kwargs) |
| 49 | + |
| 50 | + return self |
| 51 | + |
| 52 | + @classmethod |
| 53 | + def __prepare__(metacls, name, bases): |
| 54 | + return OrderedDict() |
| 55 | + |
| 56 | + class NewObject(metaclass=NewType): |
| 57 | + @classmethod |
| 58 | + def __init_subclass__(cls, **kwargs): |
| 59 | + pass |
| 60 | + |
| 61 | +else: |
| 62 | + NewType = type |
| 63 | + NewObject = object |
0 commit comments