-
Notifications
You must be signed in to change notification settings - Fork 1
/
thingy.py
219 lines (172 loc) · 5.84 KB
/
thingy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import re
from collections import OrderedDict
class classproperty(property):
def __init__(self, function):
property.__init__(self, function)
self.function_name = function.__name__
def __get__(self, instance, cls):
if instance:
try:
return instance.__dict__[self.function_name]
except KeyError:
raise AttributeError(
"'{}' object has no attribute '{}' (but its class has!)".format(
cls.__name__, self.function_name
)
)
return self.fget(cls)
class View(object):
"""Transform an :class:`object` into a dict
:param bool defaults: Include attributes of object
:param list include: A list of properties to include
:param list exclude: A list of attributes to exclude
:param bool ordered: Use an :class:`OrderedDict` instead
"""
def __init__(self, defaults=False, include=None, exclude=None, ordered=False):
self.defaults = defaults
if isinstance(include, str):
include = [include]
self.include = include or []
if isinstance(exclude, str):
exclude = [exclude]
self.exclude = exclude or []
self.ordered = ordered
def __call__(self, thingy):
if self.ordered:
d = OrderedDict()
else:
d = dict()
if not isinstance(thingy, Thingy):
return d
for attr in self.include:
key = attr
if isinstance(attr, tuple):
attr, key = attr
d.update({key: getattr(thingy, attr)})
if self.defaults:
for key, value in thingy.__dict__.items():
d.setdefault(key, value)
for field in self.exclude:
d.pop(field, None)
return d
registry = []
class ThingyMetaClass(type):
def __new__(cls, name, bases, attrs):
attrs.setdefault("_views", {})
klass = type.__new__(cls, name, bases, attrs)
if "defaults" not in klass._views:
klass.add_view("defaults", defaults=True)
registry.append(klass)
return klass
def getclassattr(instance, attr):
for cls in type(instance).mro():
try:
return cls.__dict__[attr]
except KeyError:
pass
class Thingy(object, metaclass=ThingyMetaClass):
"""Allows you to use object notation instead of dict notation"""
_view_cls = View
_silent = True
def __init__(self, *args, **kwargs):
self._update(*args, **kwargs)
def __setattr__(self, attr, value):
try:
object.__setattr__(self, attr, value)
except AttributeError:
if type(getclassattr(self, attr)) is not classproperty:
raise
self.__dict__[attr] = value
def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except AttributeError:
if type(getclassattr(self, attr)) is not property and self._silent:
return None
raise
def __eq__(self, other):
if isinstance(other, Thingy):
return self.__dict__ == other.__dict__
return super().__eq__(other)
def __repr__(self):
return "{}({})".format(self.__class__.__name__, self.__dict__)
@classmethod
def add_view(cls, name, *args, **kwargs):
cls._views.update({name: cls._view_cls(*args, **kwargs)})
def _update(self, *args, **kwargs):
for arg in args:
self.__dict__.update(**arg)
for k in kwargs:
setattr(self, k, kwargs[k])
def update(self, *args, **kwargs):
self._update(*args, **kwargs)
def view(self, name="defaults"):
return self._views[name](self)
names_regex = re.compile("([A-Z]+(?![a-z])|[A-Z][a-z]+)")
class NamesMixin(object):
@classmethod
def get_names(cls):
names = names_regex.findall(cls.__name__)
return [name.lower() for name in names]
@classproperty
def names(cls):
return cls.get_names()
class DatabaseThingy(NamesMixin, Thingy):
_database = None
_table = None
_database_name = None
_table_name = None
@classmethod
def _get_database(cls, table, name):
raise AttributeError("Undefined database.")
@classmethod
def _get_table(cls, database, name):
raise AttributeError("Undefined table.")
@classmethod
def _get_database_name(cls, database):
pass
@classmethod
def _get_table_name(cls, table):
pass
@classmethod
def get_database(cls):
if cls._database is not None:
return cls._database
return cls._get_database(cls._table, cls.database_name)
@classmethod
def get_table(cls):
if cls._table is not None:
return cls._table
return cls._get_table(cls.database, cls.table_name)
@classmethod
def get_database_name(cls):
if cls._database is not None:
return cls._get_database_name(cls._database)
if cls._database_name:
return cls._database_name
try:
return cls.names[-2]
except IndexError:
pass
@classmethod
def get_table_name(cls):
if cls._table is not None:
return cls._get_table_name(cls._table)
if cls._table_name:
return cls._table_name
if cls._database is not None or cls._database_name:
return "_".join(cls.names)
return cls.names[-1]
@classproperty
def database(cls):
return cls.get_database()
@classproperty
def table(cls):
return cls.get_table()
@classproperty
def database_name(cls):
return cls.get_database_name()
@classproperty
def table_name(cls):
return cls.get_table_name()
__all__ = ["View", "registry", "Thingy", "DatabaseThingy"]