Skip to content

Commit 0c1e7d1

Browse files
author
Marcin Kościelnicki
committed
ssot: Add a backport of PEP487 for Python <3.6
1 parent 9e6b83e commit 0c1e7d1

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

ssot/gentype.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from .pep487 import NewObject
2+
13
def name_to_words(name):
24
res = []
35
state = 'empty'
@@ -44,7 +46,7 @@ def name_to_words(name):
4446
return res
4547

4648

47-
class GenType:
49+
class GenType(NewObject):
4850
class_prefix = ""
4951

5052
def __init__(self, name, bases, ns):

ssot/pep487.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

Comments
 (0)