-
Notifications
You must be signed in to change notification settings - Fork 66
/
_attrdict.py
504 lines (441 loc) · 16.2 KB
/
_attrdict.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# Copyright (c) 2013 Brendan Curran-Johnson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Functions and Classes from attrdict.
*rmartin Feb 2021
AttrDict finally broke with Python 3.10 since abstract base classes can no
longer be imported from collections but should use collections.abc instead.
Since AttrDict is abandoned, I've consolidated the code here for future use.
AttrMap and AttrDefault are left for posterity but commented out.
"""
from __future__ import annotations
from abc import ABCMeta
from abc import abstractmethod
from re import match as re_match
from typing import Any
from typing import Dict
from typing import Mapping
from typing import MutableMapping
from typing import Sequence
from typing import TypeVar
K = TypeVar("K")
V = TypeVar("V")
T = TypeVar("T")
KOther = TypeVar("KOther")
VOther = TypeVar("VOther")
def merge(left: Mapping[K, V], right: Mapping[K, V]) -> dict[K, V]:
"""
Merge two mappings objects together, combining overlapping Mappings, and
favoring right-values.
left: The left Mapping object.
right: The right (favored) Mapping object.
NOTE: This is not commutative (merge(a,b) != merge(b,a)).
"""
merged = {}
left_keys = frozenset(left)
right_keys = frozenset(right)
# Items only in the left Mapping
for key in left_keys - right_keys:
merged[key] = left[key]
# Items only in the right Mapping
for key in right_keys - left_keys:
merged[key] = right[key]
# in both
for key in left_keys & right_keys:
left_value = left[key]
right_value = right[key]
# recursive merge
if isinstance(left_value, Mapping) and isinstance(right_value, Mapping):
merged[key] = merge(left_value, right_value) # type: ignore
# overwrite with right value
else:
merged[key] = right_value
return merged
class Attr(Mapping[K, V], metaclass=ABCMeta):
"""
A ``mixin`` class for a mapping that allows for attribute-style access of
values.
A key may be used as an attribute if:
* It is a string
* It matches ``^[A-Za-z][A-Za-z0-9_]*$`` (i.e., a public attribute)
* The key doesn't overlap with any class attributes (for ``Attr``,
those would be ``get``, ``items``, ``keys``, ``values``, ``mro``, and
``register``).
If a value which is accessed as an attribute is a Sequence-type
(and is not a string/bytes), it will be converted to a
_sequence_type with any mappings within it converted to Attrs.
NOTE:
This means that if _sequence_type is not None, then a
sequence accessed as an attribute will be a different object
than if accessed as an attribute than if it is accessed as an
item.
"""
@abstractmethod
def _configuration(self) -> Any:
"""All required state for building a new instance with the same
settings as the current object."""
@classmethod
@abstractmethod
def _constructor(cls, mapping: Mapping[K, V], configuration: Any) -> Attr[K, V]:
"""
A standardized constructor used internally by Attr.
mapping: A mapping of key-value pairs. It is HIGHLY recommended
that you use this as the internal key-value pair mapping, as
that will allow nested assignment (e.g., attr.foo.bar = baz)
configuration: The return value of Attr._configuration
"""
def __call__(self, key: K) -> Attr[K, V]:
"""
Dynamically access a key-value pair.
key: A key associated with a value in the mapping.
This differs from __getitem__, because it returns a new instance
of an Attr (if the value is a Mapping object).
"""
if key not in self:
raise AttributeError(
f"'{self.__class__.__name__} instance has no attribute '{key}'"
)
return self._build(self[key])
def __getattr__(self, key: Any) -> Any:
"""Access an item as an attribute."""
if key not in self or not self._valid_name(key):
raise AttributeError(
f"'{self.__class__.__name__}' instance has no attribute '{key}'"
)
return self._build(self[key])
def __add__(self, other: Mapping[K, V]) -> Attr[K, V]:
"""
Add a mapping to this Attr, creating a new, merged Attr.
other: A mapping.
NOTE: Addition is not commutative. a + b != b + a.
"""
if not isinstance(other, Mapping):
return NotImplemented # type: ignore
return self._constructor(merge(self, other), self._configuration())
def __radd__(self, other: Mapping[K, V]) -> Attr[K, V]:
"""
Add this Attr to a mapping, creating a new, merged Attr.
other: A mapping.
NOTE: Addition is not commutative. a + b != b + a.
"""
if not isinstance(other, Mapping):
return NotImplemented # type: ignore
return self._constructor(merge(other, self), self._configuration())
def _build(self, obj: Any) -> AttrDict[K, V]:
"""
Conditionally convert an object to allow for recursive mapping access.
obj: An object that was a key-value pair in the mapping. If obj
is a mapping, self._constructor(obj, self._configuration())
will be called. If obj is a non-string/bytes sequence, and
self._sequence_type is not None, the obj will be converted
to type _sequence_type and build will be called on its
elements.
"""
if isinstance(obj, Mapping):
obj = self._constructor(obj, self._configuration())
elif isinstance(obj, Sequence) and not isinstance(obj, (str, bytes)):
sequence_type = getattr(self, "_sequence_type", None)
if sequence_type:
obj = sequence_type(self._build(element) for element in obj)
return obj # type: ignore
@classmethod
def _valid_name(cls, key: Any) -> bool:
"""
Check whether a key is a valid attribute name.
A key may be used as an attribute if:
* It is a string
* It matches /^[A-Za-z][A-Za-z0-9_]*$/ (i.e., a public attribute)
* The key doesn't overlap with any class attributes (for Attr,
those would be 'get', 'items', 'keys', 'values', 'mro', and
'register').
"""
return bool(
isinstance(key, str)
and re_match("^[A-Za-z][A-Za-z0-9_]*$", key)
and not hasattr(cls, key)
)
class MutableAttr(Attr[K, V], MutableMapping[K, V], metaclass=ABCMeta):
"""A ``mixin`` mapping class that allows for attribute-style access of values."""
def _setattr(self, key: str, value: Any) -> None:
"""Add an attribute to the object, without attempting to add it as a
key to the mapping."""
super().__setattr__(key, value)
def __setattr__(self, key: str, value: V) -> None:
"""
Add an attribute.
key: The name of the attribute
value: The attributes contents
"""
if self._valid_name(key):
self[key] = value # type: ignore
elif getattr(self, "_allow_invalid_attributes", True):
super().__setattr__(key, value)
else:
raise TypeError(
"'{cls}' does not allow attribute creation.".format(
cls=self.__class__.__name__
)
)
def _delattr(self, key: str) -> None:
"""Delete an attribute from the object, without attempting to remove it
from the mapping."""
super().__delattr__(key)
def __delattr__(self, key: str, force: bool = False) -> None: # type: ignore
"""
Delete an attribute.
key: The name of the attribute
"""
if self._valid_name(key):
del self[key] # type: ignore
elif getattr(self, "_allow_invalid_attributes", True):
super().__delattr__(key)
else:
raise TypeError(
"'{cls}' does not allow attribute deletion.".format(
cls=self.__class__.__name__
)
)
class AttrDict(Dict[K, V], MutableAttr[K, V]):
"""A dict that implements MutableAttr."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._setattr("_sequence_type", tuple)
self._setattr("_allow_invalid_attributes", False)
def _configuration(self) -> Any:
"""The configuration for an attrmap instance."""
return self._sequence_type
def __getstate__(self) -> Any:
"""Serialize the object."""
return self.copy(), self._sequence_type, self._allow_invalid_attributes
def __setstate__(self, state: Any) -> None:
"""Deserialize the object."""
mapping, sequence_type, allow_invalid_attributes = state
self.update(mapping)
self._setattr("_sequence_type", sequence_type)
self._setattr("_allow_invalid_attributes", allow_invalid_attributes)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
@classmethod
def _constructor(cls, mapping: Mapping[K, V], configuration: Any) -> AttrDict[K, V]:
"""A standardized constructor."""
attr = cls(mapping)
attr._setattr("_sequence_type", configuration)
return attr
# class AttrMap(MutableAttr):
# """
# An implementation of MutableAttr.
# """
# def __init__(self, items=None, sequence_type=tuple):
# if items is None:
# items = {}
# elif not isinstance(items, Mapping):
# items = dict(items)
#
# self._setattr('_sequence_type', sequence_type)
# self._setattr('_mapping', items)
# self._setattr('_allow_invalid_attributes', False)
#
# def _configuration(self):
# """
# The configuration for an attrmap instance.
# """
# return self._sequence_type
#
# def __getitem__(self, key):
# """
# Access a value associated with a key.
# """
# return self._mapping[key]
#
# def __setitem__(self, key, value):
# """
# Add a key-value pair to the instance.
# """
# self._mapping[key] = value
#
# def __delitem__(self, key):
# """
# Delete a key-value pair
# """
# del self._mapping[key]
#
# def __len__(self):
# """
# Check the length of the mapping.
# """
# return len(self._mapping)
#
# def __iter__(self):
# """
# Iterated through the keys.
# """
# return iter(self._mapping)
#
# def __repr__(self):
# """
# Return a string representation of the object.
# """
# # sequence type seems like more trouble than it is worth.
# # If people want full serialization, they can pickle, and in
# # 99% of cases, sequence_type won't change anyway
# return six.u("AttrMap({mapping})").format(mapping=repr(self._mapping))
#
# def __getstate__(self):
# """
# Serialize the object.
# """
# return (
# self._mapping,
# self._sequence_type,
# self._allow_invalid_attributes
# )
#
# def __setstate__(self, state):
# """
# Deserialize the object.
# """
# mapping, sequence_type, allow_invalid_attributes = state
# self._setattr('_mapping', mapping)
# self._setattr('_sequence_type', sequence_type)
# self._setattr('_allow_invalid_attributes', allow_invalid_attributes)
#
# @classmethod
# def _constructor(cls, mapping, configuration):
# """
# A standardized constructor.
# """
# return cls(mapping, sequence_type=configuration)
# class AttrDefault(MutableAttr):
# """
# An implementation of MutableAttr with defaultdict support
# """
# def __init__(self, default_factory=None, items=None, sequence_type=tuple,
# pass_key=False):
# if items is None:
# items = {}
# elif not isinstance(items, Mapping):
# items = dict(items)
#
# self._setattr('_default_factory', default_factory)
# self._setattr('_mapping', items)
# self._setattr('_sequence_type', sequence_type)
# self._setattr('_pass_key', pass_key)
# self._setattr('_allow_invalid_attributes', False)
#
# def _configuration(self):
# """
# The configuration for a AttrDefault instance
# """
# return self._sequence_type, self._default_factory, self._pass_key
#
# def __getitem__(self, key):
# """
# Access a value associated with a key.
#
# Note: values returned will not be wrapped, even if recursive
# is True.
# """
# if key in self._mapping:
# return self._mapping[key]
# elif self._default_factory is not None:
# return self.__missing__(key)
#
# raise KeyError(key)
#
# def __setitem__(self, key, value):
# """
# Add a key-value pair to the instance.
# """
# self._mapping[key] = value
#
# def __delitem__(self, key):
# """
# Delete a key-value pair
# """
# del self._mapping[key]
#
# def __len__(self):
# """
# Check the length of the mapping.
# """
# return len(self._mapping)
#
# def __iter__(self):
# """
# Iterated through the keys.
# """
# return iter(self._mapping)
#
# def __missing__(self, key):
# """
# Add a missing element.
# """
# if self._pass_key:
# self[key] = value = self._default_factory(key)
# else:
# self[key] = value = self._default_factory()
#
# return value
#
# def __repr__(self):
# """
# Return a string representation of the object.
# """
# return six.u(
# "AttrDefault({default_factory}, {pass_key}, {mapping})"
# ).format(
# default_factory=repr(self._default_factory),
# pass_key=repr(self._pass_key),
# mapping=repr(self._mapping),
# )
#
# def __getstate__(self):
# """
# Serialize the object.
# """
# return (
# self._default_factory,
# self._mapping,
# self._sequence_type,
# self._pass_key,
# self._allow_invalid_attributes,
# )
#
# def __setstate__(self, state):
# """
# Deserialize the object.
# """
# (default_factory, mapping, sequence_type, pass_key,
# allow_invalid_attributes) = state
#
# self._setattr('_default_factory', default_factory)
# self._setattr('_mapping', mapping)
# self._setattr('_sequence_type', sequence_type)
# self._setattr('_pass_key', pass_key)
# self._setattr('_allow_invalid_attributes', allow_invalid_attributes)
#
# @classmethod
# def _constructor(cls, mapping, configuration):
# """
# A standardized constructor.
# """
# sequence_type, default_factory, pass_key = configuration
# return cls(default_factory, mapping, sequence_type=sequence_type,
# pass_key=pass_key)