1
|
|
|
""" |
2
|
|
|
Code for decorateme. |
3
|
|
|
""" |
4
|
|
|
from __future__ import annotations |
5
|
|
|
|
6
|
|
|
import enum |
7
|
|
|
import html as _html |
8
|
|
|
import logging |
9
|
|
|
|
10
|
|
|
# noinspection PyUnresolvedReferences |
11
|
|
|
from abc import abstractmethod |
12
|
|
|
from collections.abc import Callable, Collection |
13
|
|
|
|
14
|
|
|
# noinspection PyUnresolvedReferences |
15
|
|
|
from functools import total_ordering, wraps |
16
|
|
|
from importlib.metadata import PackageNotFoundError |
|
|
|
|
17
|
|
|
from importlib.metadata import metadata as __load |
|
|
|
|
18
|
|
|
from pathlib import Path |
19
|
|
|
|
20
|
|
|
# noinspection PyUnresolvedReferences |
21
|
|
|
from typing import Literal, TypeVar, final |
|
|
|
|
22
|
|
|
from warnings import warn |
23
|
|
|
|
24
|
|
|
pkg = Path(__file__).absolute().parent.name |
25
|
|
|
logger = logging.getLogger(pkg) |
26
|
|
|
metadata = None |
|
|
|
|
27
|
|
|
try: |
28
|
|
|
metadata = __load(pkg) |
29
|
|
|
__status__ = "Stable" |
30
|
|
|
__copyright__ = "Copyright 2017–2022" |
31
|
|
|
__date__ = "2020-08-24" |
32
|
|
|
__uri__ = metadata["home-page"] |
33
|
|
|
__title__ = metadata["name"] |
34
|
|
|
__summary__ = metadata["summary"] |
35
|
|
|
__license__ = metadata["license"] |
36
|
|
|
__version__ = metadata["version"] |
37
|
|
|
__author__ = metadata["author"] |
38
|
|
|
__maintainer__ = metadata["maintainer"] |
39
|
|
|
__contact__ = metadata["maintainer"] |
40
|
|
|
except PackageNotFoundError: # pragma: no cover |
41
|
|
|
logger.error(f"Could not load package metadata for {pkg}. Is it installed?") |
|
|
|
|
42
|
|
|
|
43
|
|
|
|
44
|
|
|
T = TypeVar("T", bound=type) |
|
|
|
|
45
|
|
|
|
46
|
|
|
|
47
|
|
|
def reserved(cls: T) -> T: |
48
|
|
|
""" |
49
|
|
|
Empty but is declared for future use. |
50
|
|
|
""" |
51
|
|
|
return cls |
52
|
|
|
|
53
|
|
|
|
54
|
|
|
class CodeIncompleteError(NotImplementedError): |
55
|
|
|
"""The code is not finished.""" |
56
|
|
|
|
57
|
|
|
|
58
|
|
|
class CodeRemovedError(NotImplementedError): |
59
|
|
|
"""The code was removed.""" |
60
|
|
|
|
61
|
|
|
|
62
|
|
|
class PreviewWarning(UserWarning): |
63
|
|
|
"""The code being called is a preview, unstable. or immature.""" |
64
|
|
|
|
65
|
|
|
|
66
|
|
|
@enum.unique |
67
|
|
|
class CodeStatus(enum.Enum): |
68
|
|
|
""" |
69
|
|
|
An enum for the quality/maturity of code, |
70
|
|
|
ranging from incomplete to deprecated. |
71
|
|
|
""" |
72
|
|
|
|
73
|
|
|
INCOMPLETE = -2 |
74
|
|
|
PREVIEW = -1 |
75
|
|
|
STABLE = 0 |
76
|
|
|
PENDING_DEPRECATION = 1 |
77
|
|
|
DEPRECATED = 2 |
78
|
|
|
REMOVED = 3 |
79
|
|
|
|
80
|
|
|
@classmethod |
81
|
|
|
def of(cls, x: int | str | CodeStatus) -> CodeStatus: |
|
|
|
|
82
|
|
|
if isinstance(x, str): |
83
|
|
|
return cls[x.lower().strip()] |
84
|
|
|
if isinstance(x, CodeStatus): |
85
|
|
|
return x |
86
|
|
|
if isinstance(x, int): |
87
|
|
|
return cls(x) |
88
|
|
|
raise TypeError(f"Invalid type {type(x)} for {x}") |
89
|
|
|
|
90
|
|
|
|
91
|
|
|
def status( |
|
|
|
|
92
|
|
|
level: int | str | CodeStatus, |
|
|
|
|
93
|
|
|
vr: str | None = "", |
|
|
|
|
94
|
|
|
msg: str | None = None, |
|
|
|
|
95
|
|
|
): |
96
|
|
|
""" |
97
|
|
|
Annotate code quality. Emits a warning if bad code is called. |
98
|
|
|
|
99
|
|
|
Args: |
100
|
|
|
level: The quality / maturity |
101
|
|
|
vr: First version the status / warning applies to |
102
|
|
|
msg: Explanation and/or when it will be removed or completed |
103
|
|
|
""" |
104
|
|
|
|
105
|
|
|
level = CodeStatus.of(level) |
106
|
|
|
|
107
|
|
|
@wraps(status) |
108
|
|
|
def dec(func): |
109
|
|
|
func.__status__ = level |
110
|
|
|
if level is CodeStatus.STABLE: |
|
|
|
|
111
|
|
|
return func |
112
|
|
|
elif level is CodeStatus.REMOVED: |
113
|
|
|
|
114
|
|
|
def my_fn(*_, **__): |
115
|
|
|
raise CodeRemovedError(f"{func.__name__} was removed (as of version: {vr}). {msg}") |
116
|
|
|
|
117
|
|
|
return wraps(func)(my_fn) |
118
|
|
|
|
119
|
|
|
elif level is CodeStatus.INCOMPLETE: |
120
|
|
|
|
121
|
|
|
def my_fn(*_, **__): |
122
|
|
|
raise CodeIncompleteError( |
123
|
|
|
f"{func.__name__} is incomplete (as of version: {vr}). {msg}" |
124
|
|
|
) |
125
|
|
|
|
126
|
|
|
return wraps(func)(my_fn) |
127
|
|
|
elif level is CodeStatus.PREVIEW: |
128
|
|
|
|
129
|
|
|
def my_fn(*args, **kwargs): |
130
|
|
|
warn( |
131
|
|
|
f"{func.__name__} is a preview or immature (as of version: {vr}). {msg}", |
132
|
|
|
PreviewWarning, |
133
|
|
|
) |
134
|
|
|
return func(*args, **kwargs) |
135
|
|
|
|
136
|
|
|
return wraps(func)(my_fn) |
137
|
|
|
elif level is CodeStatus.PENDING_DEPRECATION: |
138
|
|
|
|
139
|
|
|
def my_fn(*args, **kwargs): |
140
|
|
|
warn( |
141
|
|
|
f"{func.__name__} is pending deprecation (as of version: {vr}). {msg}", |
142
|
|
|
PendingDeprecationWarning, |
143
|
|
|
) |
144
|
|
|
return func(*args, **kwargs) |
145
|
|
|
|
146
|
|
|
return wraps(func)(my_fn) |
147
|
|
|
elif level is CodeStatus.DEPRECATED: |
148
|
|
|
|
149
|
|
|
def my_fn(*args, **kwargs): |
150
|
|
|
warn( |
151
|
|
|
f"{func.__name__} is deprecated (as of version: {vr}). {msg}", |
152
|
|
|
DeprecationWarning, |
153
|
|
|
) |
154
|
|
|
return func(*args, **kwargs) |
155
|
|
|
|
156
|
|
|
return wraps(func)(my_fn) |
157
|
|
|
raise AssertionError(f"What is {level}?") |
158
|
|
|
|
159
|
|
|
return dec |
160
|
|
|
|
161
|
|
|
|
162
|
|
|
def incomplete( |
|
|
|
|
163
|
|
|
vr: str | None = "", |
|
|
|
|
164
|
|
|
msg: str | None = None, |
|
|
|
|
165
|
|
|
): |
166
|
|
|
return status(CodeStatus.INCOMPLETE, vr, msg) |
167
|
|
|
|
168
|
|
|
|
169
|
|
|
def preview( |
|
|
|
|
170
|
|
|
vr: str | None = "", |
|
|
|
|
171
|
|
|
msg: str | None = None, |
|
|
|
|
172
|
|
|
): |
173
|
|
|
return status(CodeStatus.PREVIEW, vr, msg) |
174
|
|
|
|
175
|
|
|
|
176
|
|
|
def pending_deprecation( |
|
|
|
|
177
|
|
|
vr: str | None = "", |
|
|
|
|
178
|
|
|
msg: str | None = None, |
|
|
|
|
179
|
|
|
): |
180
|
|
|
return status(CodeStatus.PENDING_DEPRECATION, vr, msg) |
181
|
|
|
|
182
|
|
|
|
183
|
|
|
def deprecated( |
|
|
|
|
184
|
|
|
vr: str | None = "", |
|
|
|
|
185
|
|
|
msg: str | None = None, |
|
|
|
|
186
|
|
|
): |
187
|
|
|
return status(CodeStatus.DEPRECATED, vr, msg) |
188
|
|
|
|
189
|
|
|
|
190
|
|
|
def removed( |
|
|
|
|
191
|
|
|
vr: str | None = "", |
|
|
|
|
192
|
|
|
msg: str | None = None, |
|
|
|
|
193
|
|
|
): |
194
|
|
|
return status(CodeStatus.REMOVED, vr, msg) |
195
|
|
|
|
196
|
|
|
|
197
|
|
|
class _SpecialStr(str): |
198
|
|
|
""" |
199
|
|
|
A string that can be displayed with Jupyter with line breaks and tabs. |
200
|
|
|
""" |
201
|
|
|
|
202
|
|
|
def _repr_html_(self): |
203
|
|
|
return str(self.replace("\n", "<br />").replace("\t", "    ")) |
204
|
|
|
|
205
|
|
|
|
206
|
|
|
class _Utils: |
207
|
|
|
@classmethod |
208
|
|
|
def exclude_fn(cls, *items) -> Callable[str, bool]: |
|
|
|
|
209
|
|
|
fns = [cls._exclude_fn(x) for x in items] |
210
|
|
|
|
211
|
|
|
def exclude(s: str): |
|
|
|
|
212
|
|
|
return any((fn(s) for fn in fns)) |
|
|
|
|
213
|
|
|
|
214
|
|
|
return exclude |
215
|
|
|
|
216
|
|
|
@classmethod |
217
|
|
|
def _exclude_fn(cls, exclude) -> Callable[str, bool]: |
|
|
|
|
218
|
|
|
if exclude is None or exclude is False: |
219
|
|
|
return lambda s: False |
220
|
|
|
if isinstance(exclude, str): |
|
|
|
|
221
|
|
|
return lambda s: s == exclude |
222
|
|
|
elif isinstance(exclude, Collection): |
223
|
|
|
return lambda s: s in exclude |
224
|
|
|
elif callable(exclude): |
225
|
|
|
return exclude |
226
|
|
|
else: |
227
|
|
|
raise TypeError(str(exclude)) |
228
|
|
|
|
229
|
|
|
@classmethod |
230
|
|
|
def gen_str( |
|
|
|
|
231
|
|
|
cls, |
|
|
|
|
232
|
|
|
obj, |
|
|
|
|
233
|
|
|
fields: Collection[str] = None, |
|
|
|
|
234
|
|
|
*, |
|
|
|
|
235
|
|
|
exclude: Callable[[str], bool] = lambda _: False, |
|
|
|
|
236
|
|
|
address: bool = False, |
|
|
|
|
237
|
|
|
angular: bool = False, |
|
|
|
|
238
|
|
|
): |
239
|
|
|
_name = obj.__class__.__name__ |
240
|
|
|
_fields = ", ".join( |
241
|
|
|
k + "=" + ('"' + v + '"' if isinstance(v, str) else str(v)) |
242
|
|
|
for k, v in cls.gen_list(obj, fields, exclude=exclude, address=address) |
243
|
|
|
) |
244
|
|
|
if angular: |
|
|
|
|
245
|
|
|
return f"<{_name} {_fields}>" |
246
|
|
|
else: |
247
|
|
|
return f"{_name}({_fields})" |
248
|
|
|
|
249
|
|
|
@classmethod |
250
|
|
|
def gen_html( |
|
|
|
|
251
|
|
|
cls, |
|
|
|
|
252
|
|
|
obj, |
|
|
|
|
253
|
|
|
fields: Collection[str] = None, |
|
|
|
|
254
|
|
|
*, |
|
|
|
|
255
|
|
|
exclude: Callable[[str], bool] = lambda _: False, |
|
|
|
|
256
|
|
|
address: bool = True, |
|
|
|
|
257
|
|
|
angular: bool = True, |
|
|
|
|
258
|
|
|
): |
259
|
|
|
_name = obj.__class__.__name__ |
260
|
|
|
_fields = ", ".join( |
261
|
|
|
f"{k}={_html.escape(v)}" |
262
|
|
|
for k, v in cls.gen_list(obj, fields, exclude=exclude, address=address) |
263
|
|
|
) |
264
|
|
|
if angular: |
|
|
|
|
265
|
|
|
return f"<<strong>{_name}</strong> {_fields}>" |
266
|
|
|
else: |
267
|
|
|
return f"{_name}({_fields})" |
268
|
|
|
|
269
|
|
|
@classmethod |
270
|
|
|
def gen_list( |
|
|
|
|
271
|
|
|
cls, |
|
|
|
|
272
|
|
|
obj, |
|
|
|
|
273
|
|
|
fields: Collection[str] = None, |
|
|
|
|
274
|
|
|
*, |
|
|
|
|
275
|
|
|
exclude: Callable[[str], bool] = lambda _: False, |
|
|
|
|
276
|
|
|
address: bool = False, |
|
|
|
|
277
|
|
|
): |
278
|
|
|
yield from _Utils.var_items(obj, fields, exclude=exclude) |
279
|
|
|
if address: |
280
|
|
|
yield "@", str(hex(id(obj))) |
281
|
|
|
|
282
|
|
|
@classmethod |
283
|
|
|
def var_items(cls, obj, fields, exclude): |
|
|
|
|
284
|
|
|
yield from [ |
285
|
|
|
(key, value) |
286
|
|
|
for key, value in vars(obj).items() |
287
|
|
|
if (fields is None) or (key in fields) |
288
|
|
|
if not key.startswith(f"_{obj.__class__.__name__}__") # imperfect exclude mangled |
289
|
|
|
and not exclude(key) |
290
|
|
|
] |
291
|
|
|
|
292
|
|
|
|
293
|
|
|
def add_reprs( |
|
|
|
|
294
|
|
|
fields: Collection[str] | None = None, |
|
|
|
|
295
|
|
|
*, |
|
|
|
|
296
|
|
|
exclude: Collection[str] | Callable[[str], bool] | None | Literal[False] = None, |
|
|
|
|
297
|
|
|
exclude_from_str: Collection[str] | Callable[[str], bool] | None | Literal[False] = None, |
|
|
|
|
298
|
|
|
exclude_from_repr: Collection[str] | Callable[[str], bool] | None | Literal[False] = None, |
|
|
|
|
299
|
|
|
exclude_html: Collection[str] | Callable[[str], bool] | None | Literal[False] = None, |
|
|
|
|
300
|
|
|
exclude_rich: Collection[str] | Callable[[str], bool] | None | Literal[False] = None, |
|
|
|
|
301
|
|
|
address: bool = False, |
|
|
|
|
302
|
|
|
angular: bool = False, |
|
|
|
|
303
|
|
|
html: bool = True, |
|
|
|
|
304
|
|
|
rich: bool = True, |
|
|
|
|
305
|
|
|
): |
306
|
|
|
""" |
307
|
|
|
Auto-adds ``__repr__``, ``__str__``, ``_repr_html``, and ``__rich_repr__`` |
308
|
|
|
that use instances' attributes (``vars``). |
309
|
|
|
""" |
310
|
|
|
exclude_from_repr = _Utils.exclude_fn(exclude, exclude_from_repr) |
311
|
|
|
exclude_from_str = _Utils.exclude_fn(exclude, exclude_from_str) |
312
|
|
|
exclude_html = _Utils.exclude_fn(exclude, exclude_html) |
313
|
|
|
exclude_rich = _Utils.exclude_fn(exclude, exclude_rich) |
314
|
|
|
|
315
|
|
|
def __repr(self) -> str: |
316
|
|
|
return _Utils.gen_str(self, fields, exclude=exclude_from_repr, address=address) |
317
|
|
|
|
318
|
|
|
def __str(self) -> str: |
319
|
|
|
return _Utils.gen_str(self, fields, exclude=exclude_from_str) |
320
|
|
|
|
321
|
|
|
def __html(self) -> str: |
322
|
|
|
return _Utils.gen_html(self, fields, exclude=exclude_html) |
323
|
|
|
|
324
|
|
|
if rich: |
325
|
|
|
from rich.repr import RichReprResult |
|
|
|
|
326
|
|
|
|
327
|
|
|
def __rich(self) -> RichReprResult: |
328
|
|
|
yield from _Utils.gen_list(self, fields, exclude=exclude_rich) |
329
|
|
|
|
330
|
|
|
@wraps(add_reprs) |
331
|
|
|
def dec(cls): |
332
|
|
|
if cls.__str__ is object.__str__: |
333
|
|
|
cls.__str__ = __str |
334
|
|
|
if cls.__repr__ is object.__repr__: |
335
|
|
|
cls.__repr__ = __repr |
336
|
|
|
if not hasattr(cls, "_repr_html") and html: |
337
|
|
|
cls._repr_html_ = __html |
|
|
|
|
338
|
|
|
if not hasattr(cls, "__rich_repr__") and rich: |
339
|
|
|
cls.__rich_repr__ = __rich |
|
|
|
|
340
|
|
|
cls.__rich_repr__.angular = angular |
341
|
|
|
return cls |
342
|
|
|
|
343
|
|
|
return dec |
344
|
|
|
|
345
|
|
|
|
346
|
|
|
__all__ = [ |
347
|
|
|
"abstractmethod", |
348
|
|
|
"total_ordering", |
349
|
|
|
"final", |
350
|
|
|
"CodeStatus", |
351
|
|
|
"status", |
352
|
|
|
"CodeIncompleteError", |
353
|
|
|
"PreviewWarning", |
354
|
|
|
"CodeRemovedError", |
355
|
|
|
"repr_str", |
|
|
|
|
356
|
|
|
"deprecated", |
357
|
|
|
"pending_deprecation", |
358
|
|
|
"incomplete", |
359
|
|
|
"preview", |
360
|
|
|
"removed", |
361
|
|
|
] |
362
|
|
|
|