| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
"""Classes for defining configurations of experiments and models. |
| 16 |
|
| 17 |
This file defines the classes `ConfigDict` and `FrozenConfigDict`, which are |
| 18 |
"dict-like" data structures with Lua-like access and some other nice features. |
| 19 |
Together, they are supposed to be used as a main way of expressing |
| 20 |
configurations of experiments and models. |
| 21 |
""" |
| 22 |
|
| 23 |
import abc |
| 24 |
import collections |
| 25 |
from collections import abc as collections_abc |
| 26 |
import contextlib |
| 27 |
import dataclasses |
| 28 |
import difflib |
| 29 |
import functools |
| 30 |
import inspect |
| 31 |
import json |
| 32 |
import operator |
| 33 |
import re |
| 34 |
from typing import Any, Mapping, Optional, Tuple |
| 35 |
|
| 36 |
from absl import logging |
| 37 |
import yaml |
| 38 |
from yaml import representer |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
representer.Representer.add_representer( |
| 47 |
data_type=abc.ABCMeta, |
| 48 |
representer=representer.Representer.represent_name) |
| 49 |
|
| 50 |
|
| 51 |
class RequiredValueError(Exception): |
| 52 |
pass |
| 53 |
|
| 54 |
|
| 55 |
class MutabilityError(Exception): |
| 56 |
pass |
| 57 |
|
| 58 |
|
| 59 |
class JSONDecodeError(Exception): |
| 60 |
pass |
| 61 |
|
| 62 |
_NoneType = type(None) |
| 63 |
|
| 64 |
|
| 65 |
def _is_callable_type(field_type): |
| 66 |
"""Tries to ensure: `_is_callable_type(type(obj)) == callable(obj)`.""" |
| 67 |
return any('__call__' in c.__dict__ for c in field_type.__mro__) |
| 68 |
|
| 69 |
|
| 70 |
def _is_type_safety_violation(value, field_type): |
| 71 |
"""Helper function for type safety exceptions. |
| 72 |
|
| 73 |
This function determines whether or not assigning a value to a field violates |
| 74 |
type safety. |
| 75 |
|
| 76 |
Args: |
| 77 |
value: The value to be assigned. |
| 78 |
field_type: Type of the field that we would like to assign value to. |
| 79 |
|
| 80 |
Returns: |
| 81 |
True if assigning value to field violates type safety, False otherwise. |
| 82 |
""" |
| 83 |
|
| 84 |
if value is None or field_type == _NoneType: |
| 85 |
return False |
| 86 |
elif isinstance(value, field_type): |
| 87 |
return False |
| 88 |
else: |
| 89 |
|
| 90 |
return not (callable(value) and _is_callable_type(field_type)) |
| 91 |
|
| 92 |
|
| 93 |
def _safe_cast(value, field_type, type_safe=False): |
| 94 |
"""Helper function to handle the exceptional type conversions. |
| 95 |
|
| 96 |
This function implements the following exceptions for type-checking rules: |
| 97 |
|
| 98 |
* An `int` will be converted to a `float` if overriding a `float` field. |
| 99 |
* Any string value can override a `str` or `unicode` field. The value is |
| 100 |
converted to `field_type`. |
| 101 |
* A `tuple` will be converted to a `list` if overriding a `list` field. |
| 102 |
* A `list` will be converted to a `tuple` if overriding `tuple` field. |
| 103 |
* Short and long integers are indistinguishable. The final value will always |
| 104 |
be a `long` if both types are present. |
| 105 |
|
| 106 |
Args: |
| 107 |
value: The value to be assigned. |
| 108 |
field_type: The type for the field that we would like to assign value to. |
| 109 |
type_safe: If True, the method will throw an error if the `value` is not of |
| 110 |
type `field_type` after safe type conversions. |
| 111 |
|
| 112 |
Returns: |
| 113 |
The converted type-safe version of the value if it is one of the cases |
| 114 |
described. Otherwise, return the value without conversion. |
| 115 |
|
| 116 |
Raises: |
| 117 |
TypeError: if types don't match after safe type conversions. |
| 118 |
""" |
| 119 |
original_value_type = type(value) |
| 120 |
|
| 121 |
|
| 122 |
if isinstance(value, int) and field_type is float: |
| 123 |
return float(value) |
| 124 |
|
| 125 |
|
| 126 |
if isinstance(value, str) and field_type is str: |
| 127 |
return field_type(value) |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
if isinstance(value, tuple) and field_type is list: |
| 133 |
return list(value) |
| 134 |
if isinstance(value, list) and field_type is tuple: |
| 135 |
return tuple(value) |
| 136 |
|
| 137 |
if isinstance(value, int) and field_type is int: |
| 138 |
return value |
| 139 |
|
| 140 |
if type_safe and _is_type_safety_violation(value, field_type): |
| 141 |
raise TypeError( |
| 142 |
'{} is of original type {} and cannot be casted to type {}' |
| 143 |
.format(value, str(original_value_type), str(field_type))) |
| 144 |
return value |
| 145 |
|
| 146 |
|
| 147 |
def _get_computed_value(value_or_fieldreference): |
| 148 |
if isinstance(value_or_fieldreference, FieldReference): |
| 149 |
return value_or_fieldreference.get() |
| 150 |
return value_or_fieldreference |
| 151 |
|
| 152 |
|
| 153 |
def _parse_key(key: str) -> Tuple[str, Optional[int]]: |
| 154 |
"""Parse a ConfigDict key into to it's initial part and index (if any).""" |
| 155 |
key = key.split('.')[0] |
| 156 |
index_match = re.match(r'(.*)\[([0-9]+)\]', key) |
| 157 |
if index_match: |
| 158 |
key = index_match.group(1) |
| 159 |
index = int(index_match.group(2)) |
| 160 |
else: |
| 161 |
index = None |
| 162 |
return key, index |
| 163 |
|
| 164 |
|
| 165 |
class _Op(collections.namedtuple('_Op', ['fn', 'args'])): |
| 166 |
"""A named tuple representing a lazily computed op. |
| 167 |
|
| 168 |
The _Op named tuple has two fields: |
| 169 |
fn: The function to be applied. |
| 170 |
args: a tuple/list of arguments that are used with the op. |
| 171 |
""" |
| 172 |
|
| 173 |
|
| 174 |
@functools.total_ordering |
| 175 |
class FieldReference: |
| 176 |
"""Reference to a configuration element. |
| 177 |
|
| 178 |
Typed configuration element that can take a None default value. Example:: |
| 179 |
|
| 180 |
from ml_collections import config_dict |
| 181 |
|
| 182 |
cfg_field = config_dict.FieldReference(0) |
| 183 |
cfg = config_dict.ConfigDict({ |
| 184 |
'optional': configdict.FieldReference(None, field_type=str) |
| 185 |
'field': cfg_field, |
| 186 |
'nested': {'field': cfg_field} |
| 187 |
}) |
| 188 |
|
| 189 |
with self.assertRaises(TypeError): |
| 190 |
cfg.optional = 10 # Raises an error because it's defined as an |
| 191 |
# intfield. |
| 192 |
|
| 193 |
cfg.field = 1 # Changes the value of both cfg.field and cfg.nested.field. |
| 194 |
print(cfg) |
| 195 |
|
| 196 |
This class also supports lazy computation. Example:: |
| 197 |
|
| 198 |
ref = config_dict.FieldReference(0) |
| 199 |
|
| 200 |
# Using ref in a standard operation returns another FieldReference. The new |
| 201 |
# reference ref_plus_ten will evaluate ref's value only when we call |
| 202 |
# ref_plus_ten.get() |
| 203 |
ref_plus_ten = ref + 10 |
| 204 |
|
| 205 |
ref.set(3) # change ref's value |
| 206 |
print(ref_plus_ten.get()) # Prints 13 because ref's value is 3 |
| 207 |
|
| 208 |
ref.set(-2) # change ref's value again |
| 209 |
print(ref_plus_ten.get()) # Prints 8 because ref's value is -2 |
| 210 |
""" |
| 211 |
|
| 212 |
def __init__(self, default, field_type=None, op=None, required=False): |
| 213 |
"""Creates an instance of FieldReference. |
| 214 |
|
| 215 |
Args: |
| 216 |
default: Default value. |
| 217 |
field_type: Type for the values contained by the configuration element. If |
| 218 |
None the type will be inferred from the default value. This value is |
| 219 |
used as the second argument in calls to isinstance, so it has to |
| 220 |
follow that function's requirements (class, type or a tuple containing |
| 221 |
classes, types or tuples). |
| 222 |
op: An optional operation that is applied to the underlying value when |
| 223 |
`get()` is called. |
| 224 |
required: If True, the `get()` method will raise an error if the reference |
| 225 |
does not contain a value. This argument has no effect when a default |
| 226 |
value is provided. Setting this to True will raise an error if `op` |
| 227 |
is not None. |
| 228 |
|
| 229 |
Raises: |
| 230 |
TypeError: If field_type is not None and is different from the type of the |
| 231 |
default value. |
| 232 |
ValueError: If both the default value and field_type is None. |
| 233 |
""" |
| 234 |
if field_type is None: |
| 235 |
if default is None: |
| 236 |
raise ValueError('Default value cannot be None if field_type is None') |
| 237 |
elif isinstance(default, FieldReference): |
| 238 |
field_type = default.get_type() |
| 239 |
else: |
| 240 |
field_type = type(default) |
| 241 |
else: |
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
try: |
| 247 |
isinstance(None, field_type) |
| 248 |
except TypeError: |
| 249 |
raise TypeError('field_type should be a type, not {}' |
| 250 |
.format(type(field_type))) |
| 251 |
|
| 252 |
self._field_type = field_type |
| 253 |
self.set(default) |
| 254 |
|
| 255 |
if required and op is not None: |
| 256 |
raise ValueError('Cannot set required to True if op is not None') |
| 257 |
self._required = required |
| 258 |
self._ops = [] if op is None else [op] |
| 259 |
|
| 260 |
def has_cycle(self, visited=None): |
| 261 |
"""Finds cycles in the reference graph. |
| 262 |
|
| 263 |
Args: |
| 264 |
visited: Set containing the ids of all visited nodes in the graph. The |
| 265 |
default value is the empty set. |
| 266 |
|
| 267 |
Returns: |
| 268 |
True if there is a cycle in the reference graph. |
| 269 |
""" |
| 270 |
visited = visited or set() |
| 271 |
|
| 272 |
if id(self) in visited: |
| 273 |
return True |
| 274 |
|
| 275 |
visited.add(id(self)) |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
value = self._value |
| 280 |
if isinstance(value, FieldReference) and value.has_cycle(visited.copy()): |
| 281 |
return True |
| 282 |
|
| 283 |
|
| 284 |
for op in self._ops: |
| 285 |
for arg in op.args: |
| 286 |
if isinstance(arg, FieldReference) and arg.has_cycle(visited.copy()): |
| 287 |
return True |
| 288 |
|
| 289 |
return False |
| 290 |
|
| 291 |
def set(self, value, type_safe=True): |
| 292 |
"""Overwrites the value pointed by a FieldReference. |
| 293 |
|
| 294 |
Args: |
| 295 |
value: New value. |
| 296 |
type_safe: Check that old and new values are of the same type. |
| 297 |
|
| 298 |
Raises: |
| 299 |
TypeError: If type_safe is true and old and new values are not of the same |
| 300 |
type. |
| 301 |
MutabilityError: If a cycle is found in the reference graph. |
| 302 |
""" |
| 303 |
|
| 304 |
self._ops = [] |
| 305 |
|
| 306 |
if value is None: |
| 307 |
self._value = None |
| 308 |
elif isinstance(value, FieldReference): |
| 309 |
if type_safe and not issubclass(value.get_type(), self.get_type()): |
| 310 |
raise TypeError('Reference is of type {} but should be of type {}' |
| 311 |
.format(value.get_type(), self.get_type())) |
| 312 |
old_value = getattr(self, '_value', None) |
| 313 |
self._value = value |
| 314 |
if self.has_cycle(): |
| 315 |
self._value = old_value |
| 316 |
raise MutabilityError('Found cycle in reference graph.') |
| 317 |
else: |
| 318 |
|
| 319 |
self._value = _safe_cast(value, self._field_type, type_safe) |
| 320 |
|
| 321 |
def empty(self): |
| 322 |
"""Returns True if the reference points to a None value.""" |
| 323 |
return self._value is None |
| 324 |
|
| 325 |
def get(self): |
| 326 |
"""Gets the value of the `FieldReference` object. |
| 327 |
|
| 328 |
This will dereference `_pointer` and apply all ops to its value. |
| 329 |
|
| 330 |
Returns: |
| 331 |
The result of applying all ops to the dereferenced pointer. |
| 332 |
|
| 333 |
Raises: |
| 334 |
RequiredValueError: if `required` is True and the underlying value for the |
| 335 |
reference is False. |
| 336 |
""" |
| 337 |
if self._required and self._value is None: |
| 338 |
raise RequiredValueError('None value found in required reference') |
| 339 |
|
| 340 |
value = _get_computed_value(self._value) |
| 341 |
for op in self._ops: |
| 342 |
|
| 343 |
args = [_get_computed_value(arg) for arg in op.args] |
| 344 |
if value is None or None in args: |
| 345 |
value = None |
| 346 |
logging.debug('Cannot apply `%s` to `None`; skipping.', op) |
| 347 |
else: |
| 348 |
value = op.fn(value, *args) |
| 349 |
value = _get_computed_value(value) |
| 350 |
return value |
| 351 |
|
| 352 |
def get_type(self): |
| 353 |
return self._field_type |
| 354 |
|
| 355 |
def __eq__(self, other): |
| 356 |
if isinstance(other, FieldReference): |
| 357 |
return self.get() == other.get() |
| 358 |
else: |
| 359 |
return self.get() == other |
| 360 |
|
| 361 |
def __le__(self, other): |
| 362 |
if isinstance(other, FieldReference): |
| 363 |
return self.get() <= other.get() |
| 364 |
else: |
| 365 |
return self.get() <= other |
| 366 |
|
| 367 |
|
| 368 |
__hash__ = None |
| 369 |
|
| 370 |
def _apply_op(self, fn, *args): |
| 371 |
args = [_safe_cast(arg, self._field_type) for arg in args] |
| 372 |
return FieldReference( |
| 373 |
self, |
| 374 |
field_type=self._field_type, |
| 375 |
op=_Op(fn, args)) |
| 376 |
|
| 377 |
def _apply_cast_op(self, field_type): |
| 378 |
"""Apply a cast op that changes the field_type of this FieldReference. |
| 379 |
|
| 380 |
`_apply_op` assumes that the `field_type` does not change after the op is |
| 381 |
applied whereas `_apply_cast_op` generates a FieldReference with casted |
| 382 |
field_type. |
| 383 |
|
| 384 |
Since the signature is `fn(value, *args)` we need to ignore `value` |
| 385 |
which now contains a unused default value of field_type. |
| 386 |
|
| 387 |
Args: |
| 388 |
field_type: data type to cast to. |
| 389 |
|
| 390 |
Returns: |
| 391 |
A new FieldReference with of `field_type`. |
| 392 |
""" |
| 393 |
return FieldReference( |
| 394 |
field_type(), |
| 395 |
field_type=field_type, |
| 396 |
op=_Op(lambda _, val: field_type(val), |
| 397 |
[self]), |
| 398 |
) |
| 399 |
|
| 400 |
def identity(self): |
| 401 |
return self._apply_op(lambda x: x) |
| 402 |
|
| 403 |
def attr(self, attr_name): |
| 404 |
return self._apply_op(operator.attrgetter(attr_name)) |
| 405 |
|
| 406 |
def __add__(self, other): |
| 407 |
return self._apply_op(operator.add, other) |
| 408 |
|
| 409 |
def __radd__(self, other): |
| 410 |
radd = functools.partial(operator.add, other) |
| 411 |
return self._apply_op(radd) |
| 412 |
|
| 413 |
def __sub__(self, other): |
| 414 |
return self._apply_op(operator.sub, other) |
| 415 |
|
| 416 |
def __rsub__(self, other): |
| 417 |
rsub = functools.partial(operator.sub, other) |
| 418 |
return self._apply_op(rsub) |
| 419 |
|
| 420 |
def __mul__(self, other): |
| 421 |
return self._apply_op(operator.mul, other) |
| 422 |
|
| 423 |
def __rmul__(self, other): |
| 424 |
rmul = functools.partial(operator.mul, other) |
| 425 |
return self._apply_op(rmul) |
| 426 |
|
| 427 |
def __div__(self, other): |
| 428 |
return self._apply_op(operator.truediv, other) |
| 429 |
|
| 430 |
def __rdiv__(self, other): |
| 431 |
rdiv = functools.partial(operator.truediv, other) |
| 432 |
return self._apply_op(rdiv) |
| 433 |
|
| 434 |
def __truediv__(self, other): |
| 435 |
return self._apply_op(operator.truediv, other) |
| 436 |
|
| 437 |
def __rtruediv__(self, other): |
| 438 |
rtruediv = functools.partial(operator.truediv, other) |
| 439 |
return self._apply_op(rtruediv) |
| 440 |
|
| 441 |
def __floordiv__(self, other): |
| 442 |
return self._apply_op(operator.floordiv, other) |
| 443 |
|
| 444 |
def __rfloordiv__(self, other): |
| 445 |
rfloordiv = functools.partial(operator.floordiv, other) |
| 446 |
return self._apply_op(rfloordiv) |
| 447 |
|
| 448 |
def __pow__(self, other): |
| 449 |
return self._apply_op(operator.pow, other) |
| 450 |
|
| 451 |
def __mod__(self, other): |
| 452 |
return self._apply_op(operator.mod, other) |
| 453 |
|
| 454 |
def __and__(self, other): |
| 455 |
return self._apply_op(operator.and_, other) |
| 456 |
|
| 457 |
def __or__(self, other): |
| 458 |
return self._apply_op(operator.or_, other) |
| 459 |
|
| 460 |
def __xor__(self, other): |
| 461 |
return self._apply_op(operator.xor, other) |
| 462 |
|
| 463 |
def __neg__(self): |
| 464 |
return self._apply_op(operator.neg) |
| 465 |
|
| 466 |
def __abs__(self): |
| 467 |
return self._apply_op(operator.abs) |
| 468 |
|
| 469 |
def to_int(self): |
| 470 |
return self._apply_cast_op(int) |
| 471 |
|
| 472 |
def to_float(self): |
| 473 |
return self._apply_cast_op(float) |
| 474 |
|
| 475 |
def to_str(self): |
| 476 |
return self._apply_cast_op(str) |
| 477 |
|
| 478 |
def __setstate__(self, state): |
| 479 |
self._value = state['_value'] |
| 480 |
self._field_type = state['_field_type'] |
| 481 |
self._ops = state['_ops'] |
| 482 |
|
| 483 |
|
| 484 |
self._required = state.get('_required', False) |
| 485 |
|
| 486 |
def __nonzero__(self): |
| 487 |
raise NotImplementedError( |
| 488 |
'FieldReference cannot be used for control flow. For boolean ' |
| 489 |
'operations use "&" (logical "and") or "|" (logical "or").') |
| 490 |
|
| 491 |
def __bool__(self): |
| 492 |
raise NotImplementedError( |
| 493 |
'FieldReference cannot be used for control flow. For boolean ' |
| 494 |
'operations use "&" (logical "and") or "|" (logical "or").') |
| 495 |
|
| 496 |
|
| 497 |
def _configdict_fill_seed(seed, initial_dictionary, visit_map=None): |
| 498 |
"""Fills an empty ConfigDict without copying previously visited nodes. |
| 499 |
|
| 500 |
Turns seed (an empty ConfigDict) into a ConfigDict version of |
| 501 |
initial_dictionary. Avoids infinite looping on a self-referencing |
| 502 |
initial_dictionary because if a value of initial_dictionary has been |
| 503 |
previously visited, that value is not re-converted to a ConfigDict. If a |
| 504 |
FieldReference is encountered which contains a dict or FrozenConfigDict, its |
| 505 |
contents will be converted to ConfigDict. |
| 506 |
|
| 507 |
Note: As described in the __init__() documentation, this will not |
| 508 |
replicate the structure of initial_dictionary if it contains |
| 509 |
self-references within lists, tuples, or other types. There is no warning |
| 510 |
or error in this case. |
| 511 |
|
| 512 |
Args: |
| 513 |
seed: Empty ConfigDict, to be filled in. |
| 514 |
initial_dictionary: The template on which seed is built. May be of type |
| 515 |
dict, ConfigDict or FrozenConfigDict. |
| 516 |
visit_map: Dictionary from memory addresses to values, storing the |
| 517 |
ConfigDict versions of dictionary values. visit_map need not contain |
| 518 |
(id(initial_dictionary), seed) as a key/value pair. |
| 519 |
|
| 520 |
Raises: |
| 521 |
TypeError: If seed is not a ConfigDict. |
| 522 |
ValueError: If seed is not an empty ConfigDict. |
| 523 |
""" |
| 524 |
|
| 525 |
|
| 526 |
assert isinstance(seed, ConfigDict) |
| 527 |
assert not seed |
| 528 |
|
| 529 |
visit_map = visit_map or {} |
| 530 |
visit_map[id(initial_dictionary)] = seed |
| 531 |
|
| 532 |
if isinstance(initial_dictionary, ConfigDict): |
| 533 |
iteritems = initial_dictionary.iteritems(preserve_field_references=True) |
| 534 |
else: |
| 535 |
iteritems = initial_dictionary.items() |
| 536 |
|
| 537 |
for key, value in iteritems: |
| 538 |
if id(value) in visit_map: |
| 539 |
value = visit_map[id(value)] |
| 540 |
|
| 541 |
elif (isinstance(value, FieldReference) and value.get_type() is dict |
| 542 |
and seed.convert_dict): |
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
if value.empty(): |
| 548 |
pass |
| 549 |
elif id(value.get()) in visit_map: |
| 550 |
value.set(visit_map[id(value.get())], False) |
| 551 |
else: |
| 552 |
value_cd = ConfigDict( |
| 553 |
type_safe=seed.is_type_safe, |
| 554 |
allow_dotted_keys=seed.allow_dotted_keys, |
| 555 |
) |
| 556 |
_configdict_fill_seed(value_cd, value.get(), visit_map) |
| 557 |
value.set(value_cd, False) |
| 558 |
|
| 559 |
elif isinstance(value, dict) and seed.convert_dict: |
| 560 |
value_cd = ConfigDict( |
| 561 |
type_safe=seed.is_type_safe, |
| 562 |
allow_dotted_keys=seed.allow_dotted_keys, |
| 563 |
) |
| 564 |
_configdict_fill_seed(value_cd, value, visit_map) |
| 565 |
value = value_cd |
| 566 |
|
| 567 |
elif isinstance(value, FrozenConfigDict): |
| 568 |
value = ConfigDict(value, allow_dotted_keys=seed.allow_dotted_keys) |
| 569 |
|
| 570 |
seed.__setattr__(key, value) |
| 571 |
|
| 572 |
|
| 573 |
class ConfigDict: |
| 574 |
|
| 575 |
"""Base class for configuration objects used in DeepMind. |
| 576 |
|
| 577 |
This is a container for configurations. It behaves similarly to Lua tables. |
| 578 |
Specifically: |
| 579 |
|
| 580 |
- it has dot-based access as well as dict-style key access, |
| 581 |
- it is type safe (once a value is set one cannot change its type). |
| 582 |
|
| 583 |
Typical usage example:: |
| 584 |
|
| 585 |
from ml_collections import config_dict |
| 586 |
|
| 587 |
cfg = config_dict.ConfigDict() |
| 588 |
cfg.float_field = 12.6 |
| 589 |
cfg.integer_field = 123 |
| 590 |
cfg.another_integer_field = 234 |
| 591 |
cfg.nested = config_dict.ConfigDict() |
| 592 |
cfg.nested.string_field = 'tom' |
| 593 |
|
| 594 |
print(cfg) |
| 595 |
|
| 596 |
Config dictionaries can also be used to pass named arguments to functions:: |
| 597 |
|
| 598 |
from ml_collections import config_dict |
| 599 |
|
| 600 |
def print_point(x, y): |
| 601 |
print "({},{})".format(x, y) |
| 602 |
|
| 603 |
point = config_dict.ConfigDict() |
| 604 |
point.x = 1 |
| 605 |
point.y = 2 |
| 606 |
print_point(**point) |
| 607 |
|
| 608 |
Note that, depending on your use case, it may be easier to use the `create` |
| 609 |
function in this package to construct a `ConfigDict`: |
| 610 |
|
| 611 |
from ml_collections import config_dict |
| 612 |
point = config_dict.create(x=1, y=2) |
| 613 |
|
| 614 |
Differently from standard `dicts`, `ConfigDicts` also have the nice property |
| 615 |
that iterating over them is deterministic, in a fashion similar to |
| 616 |
`collections.OrderedDicts`. |
| 617 |
""" |
| 618 |
|
| 619 |
|
| 620 |
|
| 621 |
_HAS_DYNAMIC_ATTRIBUTES = True |
| 622 |
|
| 623 |
|
| 624 |
_allow_dotted_keys: bool |
| 625 |
_sort_keys: bool |
| 626 |
|
| 627 |
def __init__( |
| 628 |
self, |
| 629 |
initial_dictionary: Optional[Mapping[str, Any]] = None, |
| 630 |
type_safe: bool = True, |
| 631 |
convert_dict: bool = True, |
| 632 |
*, |
| 633 |
allow_dotted_keys: bool = False, |
| 634 |
sort_keys: bool = True, |
| 635 |
): |
| 636 |
"""Creates an instance of ConfigDict. |
| 637 |
|
| 638 |
Warning: In most cases, this faithfully reproduces the reference structure |
| 639 |
of initial_dictionary, even if initial_dictionary is self-referencing. |
| 640 |
However, unexpected behavior occurs if self-references are contained within |
| 641 |
list, tuple, or custom types. For example:: |
| 642 |
|
| 643 |
d = {} |
| 644 |
d['a'] = d |
| 645 |
d['b'] = [d] |
| 646 |
cd = ConfigDict(d) |
| 647 |
cd.a # refers to cd, type ConfigDict. Expected behavior. |
| 648 |
cd.b # refers to d, type dict. Unexpected behavior. |
| 649 |
|
| 650 |
Warning: FieldReference values may be changed. If initial_dictionary |
| 651 |
contains a FieldReference with a value of type dict or FrozenConfigDict, |
| 652 |
that value is converted to ConfigDict. |
| 653 |
|
| 654 |
Args: |
| 655 |
initial_dictionary: May be one of the following: 1) dict. In this case, |
| 656 |
all values of initial_dictionary that are dictionaries are also be |
| 657 |
converted to ConfigDict. However, dictionaries within values of non-dict |
| 658 |
type are untouched. 2) ConfigDict. In this case, all attributes are |
| 659 |
uncopied, and only the top-level object (self) is re-addressed. This is |
| 660 |
the same behavior as Python dict, list, and tuple. 3) FrozenConfigDict. |
| 661 |
In this case, initial_dictionary is converted to a ConfigDict version of |
| 662 |
the initial dictionary for the FrozenConfigDict (reversing any |
| 663 |
mutability changes FrozenConfigDict made). |
| 664 |
type_safe: If set to True, once an attribute value is assigned, its type |
| 665 |
cannot be overridden without .ignore_type() context manager (default: |
| 666 |
True). |
| 667 |
convert_dict: If set to True, all dict used as value in the ConfigDict |
| 668 |
will automatically be converted to ConfigDict (default: True). |
| 669 |
allow_dotted_keys: If set to True, keys can contain `.`. Integer and float |
| 670 |
keys are always allowed to have dots. |
| 671 |
sort_keys: If `True` (default), keys are sorted in alphabetical order. |
| 672 |
""" |
| 673 |
|
| 674 |
if isinstance(initial_dictionary, FrozenConfigDict): |
| 675 |
initial_dictionary = initial_dictionary.as_configdict() |
| 676 |
|
| 677 |
super(ConfigDict, self).__setattr__('_fields', {}) |
| 678 |
super(ConfigDict, self).__setattr__('_locked', False) |
| 679 |
super(ConfigDict, self).__setattr__('_type_safe', type_safe) |
| 680 |
super(ConfigDict, self).__setattr__('_convert_dict', convert_dict) |
| 681 |
super(ConfigDict, self).__setattr__('_allow_dotted_keys', allow_dotted_keys) |
| 682 |
super(ConfigDict, self).__setattr__('_sort_keys', sort_keys) |
| 683 |
|
| 684 |
if initial_dictionary is not None: |
| 685 |
_configdict_fill_seed(self, initial_dictionary) |
| 686 |
|
| 687 |
if isinstance(initial_dictionary, ConfigDict): |
| 688 |
super(ConfigDict, self).__setattr__('_locked', |
| 689 |
initial_dictionary.is_locked) |
| 690 |
super(ConfigDict, self).__setattr__('_type_safe', |
| 691 |
initial_dictionary.is_type_safe) |
| 692 |
|
| 693 |
@property |
| 694 |
def is_type_safe(self) -> bool: |
| 695 |
"""Returns True if config dict is type safe.""" |
| 696 |
return self._type_safe |
| 697 |
|
| 698 |
@property |
| 699 |
def allow_dotted_keys(self) -> bool: |
| 700 |
"""Returns True if keys can contain `.`.""" |
| 701 |
return self._allow_dotted_keys |
| 702 |
|
| 703 |
@property |
| 704 |
def convert_dict(self): |
| 705 |
"""Returns True if it is converting dicts to ConfigDict automatically.""" |
| 706 |
return self._convert_dict |
| 707 |
|
| 708 |
def lock(self) -> 'ConfigDict': |
| 709 |
"""Locks object, preventing user from adding new fields. |
| 710 |
|
| 711 |
Returns: |
| 712 |
self |
| 713 |
""" |
| 714 |
|
| 715 |
if self.is_locked: |
| 716 |
return self |
| 717 |
|
| 718 |
super(ConfigDict, self).__setattr__('_locked', True) |
| 719 |
for field in self._fields: |
| 720 |
element = self._fields[field] |
| 721 |
element = _get_computed_value(element) |
| 722 |
|
| 723 |
if isinstance(element, ConfigDict): |
| 724 |
element.lock() |
| 725 |
return self |
| 726 |
|
| 727 |
@property |
| 728 |
def is_locked(self) -> bool: |
| 729 |
"""Returns True if object is locked.""" |
| 730 |
return self._locked |
| 731 |
|
| 732 |
def unlock(self) -> 'ConfigDict': |
| 733 |
"""Grants user the ability to add new fields to ConfigDict. |
| 734 |
|
| 735 |
In most cases, the unlocked() context manager should be preferred to the |
| 736 |
direct use of the unlock method. |
| 737 |
|
| 738 |
Returns: |
| 739 |
self |
| 740 |
""" |
| 741 |
super(ConfigDict, self).__setattr__('_locked', False) |
| 742 |
for element in self._fields.values(): |
| 743 |
element = _get_computed_value(element) |
| 744 |
|
| 745 |
if isinstance(element, ConfigDict) and element.is_locked: |
| 746 |
element.unlock() |
| 747 |
return self |
| 748 |
|
| 749 |
def get(self, key: str, default=None): |
| 750 |
"""Returns value if key is present, or a user defined value otherwise.""" |
| 751 |
try: |
| 752 |
return self[key] |
| 753 |
except KeyError: |
| 754 |
return default |
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
def get_ref(self, key): |
| 760 |
"""Returns a FieldReference initialized on key's value.""" |
| 761 |
field = self._fields[key] |
| 762 |
if field is None: |
| 763 |
raise ValueError('Cannot create reference to a field whose value is None') |
| 764 |
if not isinstance(field, FieldReference): |
| 765 |
field = FieldReference(field) |
| 766 |
with self.ignore_type(): |
| 767 |
self[key] = field |
| 768 |
return field |
| 769 |
|
| 770 |
def get_oneway_ref(self, key): |
| 771 |
"""Returns a one-way FieldReference. |
| 772 |
|
| 773 |
Example:: |
| 774 |
|
| 775 |
cfg = config_dict.ConfigDict(dict(a=1)) |
| 776 |
cfg.b = cfg.get_oneway_ref('a') |
| 777 |
|
| 778 |
cfg.a = 2 |
| 779 |
print(cfg.b) # 2 |
| 780 |
|
| 781 |
cfg.b = 3 |
| 782 |
print(cfg.a) # 2 (would have been 3 if using get_ref()) |
| 783 |
print(cfg.b) # 3 |
| 784 |
|
| 785 |
Args: |
| 786 |
key: Key for field we want to reference. |
| 787 |
""" |
| 788 |
|
| 789 |
|
| 790 |
|
| 791 |
return self.get_ref(key).identity() |
| 792 |
|
| 793 |
def items(self, preserve_field_references=False): |
| 794 |
"""Returns list of dictionary key, value pairs, sorted by key. |
| 795 |
|
| 796 |
Args: |
| 797 |
preserve_field_references: (bool) Whether to preserve FieldReferences if |
| 798 |
the ConfigDict has them. By default, False: any FieldReferences will be |
| 799 |
resolved in the result. |
| 800 |
|
| 801 |
Returns: |
| 802 |
The key, value pairs in the config, sorted by key. |
| 803 |
""" |
| 804 |
if preserve_field_references: |
| 805 |
return self._ordered_fields.items() |
| 806 |
else: |
| 807 |
return [(k, self[k]) for k in self._ordered_fields] |
| 808 |
|
| 809 |
@property |
| 810 |
def _ordered_fields(self): |
| 811 |
"""Returns ordered dict shallow cast of _fields member.""" |
| 812 |
if self._sort_keys: |
| 813 |
return collections.OrderedDict(sorted(self._fields.items())) |
| 814 |
else: |
| 815 |
return self._fields |
| 816 |
|
| 817 |
def iteritems(self, preserve_field_references=False): |
| 818 |
"""Deterministically iterates over dictionary key, value pairs. |
| 819 |
|
| 820 |
Args: |
| 821 |
preserve_field_references: (bool) Whether to preserve FieldReferences if |
| 822 |
the ConfigDict has them. By default, False: any FieldReferences will be |
| 823 |
resolved in the result. |
| 824 |
Yields: |
| 825 |
The key, value pairs in the config, sorted by key. |
| 826 |
""" |
| 827 |
for k in self._ordered_fields: |
| 828 |
if preserve_field_references: |
| 829 |
yield k, self._fields[k] |
| 830 |
else: |
| 831 |
yield k, self[k] |
| 832 |
|
| 833 |
def _ensure_mutability(self, attribute): |
| 834 |
if attribute in dir(super(ConfigDict, self)): |
| 835 |
raise KeyError('{} cannot be overridden.'.format(attribute)) |
| 836 |
|
| 837 |
def __setattr__(self, attribute, value): |
| 838 |
try: |
| 839 |
self._ensure_mutability(attribute) |
| 840 |
self[attribute] = value |
| 841 |
except KeyError as e: |
| 842 |
raise AttributeError(e) |
| 843 |
|
| 844 |
def __delattr__(self, attribute): |
| 845 |
try: |
| 846 |
self._ensure_mutability(attribute) |
| 847 |
del self[attribute] |
| 848 |
except KeyError as e: |
| 849 |
raise AttributeError(e) |
| 850 |
|
| 851 |
def __getattr__(self, attribute): |
| 852 |
try: |
| 853 |
return self[attribute] |
| 854 |
except KeyError as e: |
| 855 |
raise AttributeError(e) |
| 856 |
|
| 857 |
def __setitem__(self, key, value): |
| 858 |
if ( |
| 859 |
not self._allow_dotted_keys |
| 860 |
and not isinstance(key, (int, float)) |
| 861 |
and '.' in key |
| 862 |
): |
| 863 |
raise ValueError( |
| 864 |
'ConfigDict does not accept dots in field names (when' |
| 865 |
f' `allow_dotted_keys=False`), but the key {key} contains one.' |
| 866 |
) |
| 867 |
|
| 868 |
if self.is_locked and key not in self._fields: |
| 869 |
error_msg = ('Key "{}" does not exist and cannot be added since the ' |
| 870 |
'config is locked. Other fields present: "{}"') |
| 871 |
raise KeyError( |
| 872 |
self._generate_did_you_mean_message( |
| 873 |
key, error_msg.format(key, self._fields) |
| 874 |
) |
| 875 |
) |
| 876 |
|
| 877 |
if key in self._fields: |
| 878 |
field = self._fields[key] |
| 879 |
try: |
| 880 |
|
| 881 |
if isinstance(field, FieldReference): |
| 882 |
field.set(value, self._type_safe) |
| 883 |
return |
| 884 |
|
| 885 |
if not _should_skip_type_check(field, value): |
| 886 |
if isinstance(value, dict) and self._convert_dict: |
| 887 |
value = type(self)(value, type_safe=self._type_safe) |
| 888 |
value = _safe_cast(value, type(field), self._type_safe) |
| 889 |
except TypeError as e: |
| 890 |
raise TypeError( |
| 891 |
f"Could not override field '{key}' (reference). {e}" |
| 892 |
) from None |
| 893 |
|
| 894 |
if self._convert_dict: |
| 895 |
if isinstance(value, dict): |
| 896 |
value = ConfigDict(value, self._type_safe) |
| 897 |
elif isinstance(value, FieldReference): |
| 898 |
|
| 899 |
ref_type = _NoneType if value.empty() else type(value.get()) |
| 900 |
if ref_type is dict or ref_type is FrozenConfigDict: |
| 901 |
value_cd = ConfigDict(value.get(), self._type_safe) |
| 902 |
value.set(value_cd, False) |
| 903 |
|
| 904 |
self._fields[key] = value |
| 905 |
|
| 906 |
def _generate_did_you_mean_message(self, request, message=''): |
| 907 |
if isinstance(request, (int, float)): |
| 908 |
return message |
| 909 |
|
| 910 |
keys = tuple(str(k) for k in self.keys()) |
| 911 |
matches = difflib.get_close_matches(request, keys, 1, 0.75) |
| 912 |
if matches: |
| 913 |
if message: |
| 914 |
message += '\n' |
| 915 |
message += 'Did you mean "{}" instead of "{}"?'.format(matches[0], |
| 916 |
request) |
| 917 |
return message |
| 918 |
|
| 919 |
def __delitem__(self, key: str): |
| 920 |
if self.is_locked: |
| 921 |
raise KeyError('This ConfigDict is locked, you have to unlock it before ' |
| 922 |
'trying to delete a field.') |
| 923 |
|
| 924 |
if ( |
| 925 |
not self._allow_dotted_keys |
| 926 |
and not isinstance(key, (int, float)) |
| 927 |
and '.' in key |
| 928 |
): |
| 929 |
|
| 930 |
|
| 931 |
key, rest = key.split('.', 1) |
| 932 |
del self[key][rest] |
| 933 |
return |
| 934 |
|
| 935 |
try: |
| 936 |
del self._fields[key] |
| 937 |
except KeyError as e: |
| 938 |
raise KeyError(self._generate_did_you_mean_message(key, str(e))) |
| 939 |
|
| 940 |
def __getitem__(self, key: str): |
| 941 |
if ( |
| 942 |
not self._allow_dotted_keys |
| 943 |
and not isinstance(key, (int, float)) |
| 944 |
and '.' in key |
| 945 |
): |
| 946 |
|
| 947 |
|
| 948 |
key, rest = key.split('.', 1) |
| 949 |
return self[key][rest] |
| 950 |
|
| 951 |
try: |
| 952 |
field = self._fields[key] |
| 953 |
if isinstance(field, FieldReference): |
| 954 |
return field.get() |
| 955 |
else: |
| 956 |
return field |
| 957 |
except KeyError as e: |
| 958 |
raise KeyError(self._generate_did_you_mean_message(key, str(e))) |
| 959 |
|
| 960 |
def __contains__(self, key: str): |
| 961 |
return key in self._fields |
| 962 |
|
| 963 |
def __repr__(self) -> str: |
| 964 |
|
| 965 |
|
| 966 |
try: |
| 967 |
return yaml.dump(self.to_dict(preserve_field_references=True), |
| 968 |
default_flow_style=False) |
| 969 |
except Exception: |
| 970 |
return repr(self.to_dict()) |
| 971 |
|
| 972 |
def __str__(self) -> str: |
| 973 |
|
| 974 |
|
| 975 |
try: |
| 976 |
return yaml.dump(self.to_dict()) |
| 977 |
except Exception: |
| 978 |
return str(self.to_dict()) |
| 979 |
|
| 980 |
def keys(self): |
| 981 |
"""Returns the sorted list of all the keys defined in a config.""" |
| 982 |
return list(self._ordered_fields.keys()) |
| 983 |
|
| 984 |
def iterkeys(self): |
| 985 |
"""Deterministically iterates over dictionary keys, in sorted order.""" |
| 986 |
return self._ordered_fields.keys() |
| 987 |
|
| 988 |
def values(self, preserve_field_references=False): |
| 989 |
"""Returns the list of all values in a config, sorted by their keys. |
| 990 |
|
| 991 |
Args: |
| 992 |
preserve_field_references: (bool) Whether to preserve FieldReferences if |
| 993 |
the ConfigDict has them. By default, False: any FieldReferences will be |
| 994 |
resolved in the result. |
| 995 |
Returns: |
| 996 |
The values in the config, sorted by their corresponding keys. |
| 997 |
""" |
| 998 |
if preserve_field_references: |
| 999 |
return list(self._ordered_fields.values()) |
| 1000 |
else: |
| 1001 |
return [self[k] for k in self._ordered_fields] |
| 1002 |
|
| 1003 |
def itervalues(self, preserve_field_references=False): |
| 1004 |
"""Deterministically iterates over values in a config, sorted by their keys. |
| 1005 |
|
| 1006 |
Args: |
| 1007 |
preserve_field_references: (bool) Whether to preserve FieldReferences if |
| 1008 |
the ConfigDict has them. By default, False: any FieldReferences will be |
| 1009 |
resolved in the result. |
| 1010 |
Yields: |
| 1011 |
The values in the config, sorted by their corresponding keys. |
| 1012 |
""" |
| 1013 |
for k in self._ordered_fields: |
| 1014 |
if preserve_field_references: |
| 1015 |
yield self._fields[k] |
| 1016 |
else: |
| 1017 |
yield self[k] |
| 1018 |
|
| 1019 |
def __dir__(self): |
| 1020 |
return self.keys() + dir(ConfigDict) |
| 1021 |
|
| 1022 |
def __len__(self): |
| 1023 |
return self._ordered_fields.__len__() |
| 1024 |
|
| 1025 |
def __iter__(self): |
| 1026 |
return self._ordered_fields.__iter__() |
| 1027 |
|
| 1028 |
def __eq__(self, other): |
| 1029 |
"""Override the default Equals behavior.""" |
| 1030 |
if isinstance(other, self.__class__): |
| 1031 |
same = self._fields == other._fields |
| 1032 |
same &= self._locked == other.is_locked |
| 1033 |
same &= self._type_safe == other.is_type_safe |
| 1034 |
return same |
| 1035 |
return False |
| 1036 |
|
| 1037 |
def __ne__(self, other): |
| 1038 |
"""Define a non-equality test.""" |
| 1039 |
return not self.__eq__(other) |
| 1040 |
|
| 1041 |
def eq_as_configdict(self, other): |
| 1042 |
"""Type-invariant equals. |
| 1043 |
|
| 1044 |
This is like `__eq__`, except it does not distinguish `FrozenConfigDict` |
| 1045 |
from `ConfigDict`. For example:: |
| 1046 |
|
| 1047 |
cd = ConfigDict() |
| 1048 |
fcd = FrozenConfigDict() |
| 1049 |
fcd.eq_as_configdict(cd) # Returns True |
| 1050 |
|
| 1051 |
Args: |
| 1052 |
other: Object to compare self to. |
| 1053 |
|
| 1054 |
Returns: |
| 1055 |
same: `True` if `self == other` after conversion to `ConfigDict`. |
| 1056 |
""" |
| 1057 |
if isinstance(other, ConfigDict): |
| 1058 |
return ConfigDict(self) == ConfigDict(other) |
| 1059 |
else: |
| 1060 |
return False |
| 1061 |
|
| 1062 |
|
| 1063 |
__hash__ = None |
| 1064 |
|
| 1065 |
def to_yaml(self, **kwargs): |
| 1066 |
"""Returns a YAML representation of the object. |
| 1067 |
|
| 1068 |
ConfigDict serializes types of fields as well as the values of fields |
| 1069 |
themselves. Deserializing the YAML representation hence requires using |
| 1070 |
YAML's UnsafeLoader: |
| 1071 |
|
| 1072 |
``` |
| 1073 |
yaml.load(cfg.to_yaml(), Loader=yaml.UnsafeLoader) |
| 1074 |
``` |
| 1075 |
|
| 1076 |
or equivalently: |
| 1077 |
|
| 1078 |
``` |
| 1079 |
yaml.unsafe_load(cfg.to_yaml()) |
| 1080 |
``` |
| 1081 |
|
| 1082 |
Please see the PyYAML documentation and https://msg.pyyaml.org/load for more |
| 1083 |
details on the consequences of this. |
| 1084 |
|
| 1085 |
Args: |
| 1086 |
**kwargs: Keyword arguments for yaml.dump. |
| 1087 |
|
| 1088 |
Returns: |
| 1089 |
YAML representation of the object. |
| 1090 |
""" |
| 1091 |
return yaml.dump(self, **kwargs) |
| 1092 |
|
| 1093 |
def _json_dumps_wrapper(self, **kwargs): |
| 1094 |
"""Wrapper for json.dumps() method. |
| 1095 |
|
| 1096 |
Produces a more informative error message when there is a problem with |
| 1097 |
string encodings in the ConfigDict. |
| 1098 |
|
| 1099 |
Args: |
| 1100 |
**kwargs: Keyword arguments for json.dumps. |
| 1101 |
|
| 1102 |
Returns: |
| 1103 |
JSON representation of the object. |
| 1104 |
|
| 1105 |
Raises: |
| 1106 |
JSONDecodeError: If there is a problem with string encodings. |
| 1107 |
""" |
| 1108 |
try: |
| 1109 |
return json.dumps(self, **kwargs) |
| 1110 |
except UnicodeDecodeError as error: |
| 1111 |
|
| 1112 |
new_message = ( |
| 1113 |
'Decoding error. Make sure all strings in your ConfigDict use ASCII-' |
| 1114 |
'compatible encodings. See ' |
| 1115 |
'https://docs.python.org/2.7/howto/unicode.html#the-unicode-type ' |
| 1116 |
'for details. Original error message: {}'.format(error)) |
| 1117 |
raise JSONDecodeError(new_message) |
| 1118 |
|
| 1119 |
def to_json(self, json_encoder_cls=None, **kwargs): |
| 1120 |
"""Returns a JSON representation of the object, fails if there is a cycle. |
| 1121 |
|
| 1122 |
Args: |
| 1123 |
json_encoder_cls: An optional JSON encoder class to customize JSON |
| 1124 |
serialization. |
| 1125 |
**kwargs: Keyword arguments for json.dumps. They cannot contain "cls" |
| 1126 |
as this method specifies it on its own. |
| 1127 |
|
| 1128 |
Returns: |
| 1129 |
JSON representation of the object. |
| 1130 |
|
| 1131 |
Raises: |
| 1132 |
TypeError: If self contains set, frozenset, custom type fields or any |
| 1133 |
other objects that are not JSON serializable. |
| 1134 |
""" |
| 1135 |
json_encoder_cls = json_encoder_cls or CustomJSONEncoder |
| 1136 |
return self._json_dumps_wrapper(cls=json_encoder_cls, **kwargs) |
| 1137 |
|
| 1138 |
def to_json_best_effort(self, **kwargs): |
| 1139 |
"""Returns a best effort JSON representation of the object. |
| 1140 |
|
| 1141 |
Tries to serialize objects not inherently supported by JSON encoder. This |
| 1142 |
may result in the configdict being partially serialized, skipping the |
| 1143 |
unserializable bits. Ensures that no errors are thrown. Fails if there is a |
| 1144 |
cycle. |
| 1145 |
|
| 1146 |
Args: |
| 1147 |
**kwargs: Keyword arguments for json.dumps. They cannot contain "cls" |
| 1148 |
as this method specifies it on its own. |
| 1149 |
|
| 1150 |
Returns: |
| 1151 |
JSON representation of the object. |
| 1152 |
""" |
| 1153 |
return self._json_dumps_wrapper(cls=_BestEffortCustomJSONEncoder, **kwargs) |
| 1154 |
|
| 1155 |
def to_dict(self, visit_map=None, preserve_field_references=False): |
| 1156 |
"""Converts ConfigDict to regular dict recursively with valid references. |
| 1157 |
|
| 1158 |
By default, the output dict will not contain FieldReferences, any present |
| 1159 |
in the ConfigDict will be resolved. However, if `preserve_field_references` |
| 1160 |
is True, the output dict will contain FieldReferences where the original |
| 1161 |
ConfigDict has them. They will not be the same as the ConfigDict's, and |
| 1162 |
their ops will be applied and dropped. |
| 1163 |
|
| 1164 |
Note: As with __eq__() and __init__(), this may not behave as expected on a |
| 1165 |
ConfigDict with self-references contained in lists, tuples, or custom types. |
| 1166 |
|
| 1167 |
Args: |
| 1168 |
visit_map: A mapping from object ids to their dict representation. Method |
| 1169 |
is recursive in nature, and it will call ".to_dict(visit_map)" on each |
| 1170 |
encountered object, unless it is already in visit_map. |
| 1171 |
preserve_field_references: (bool) Whether the output dict should have |
| 1172 |
FieldReferences if the ConfigDict has them. By default, False: any |
| 1173 |
FieldReferences will be resolved and the result will go to the dict. |
| 1174 |
Returns: |
| 1175 |
Dictionary with the same values and references structure as a calling |
| 1176 |
ConfigDict. |
| 1177 |
""" |
| 1178 |
visit_map = visit_map or {} |
| 1179 |
dict_self = {} |
| 1180 |
visit_map[id(self)] = dict_self |
| 1181 |
|
| 1182 |
for key in self: |
| 1183 |
if (isinstance(self._fields[key], FieldReference) |
| 1184 |
and preserve_field_references): |
| 1185 |
reference = self._fields[key] |
| 1186 |
value = reference.get() |
| 1187 |
else: |
| 1188 |
value = self[key] |
| 1189 |
reference = value |
| 1190 |
|
| 1191 |
if id(reference) in visit_map: |
| 1192 |
dict_self[key] = visit_map[id(reference)] |
| 1193 |
elif isinstance(value, ConfigDict): |
| 1194 |
if isinstance(reference, FieldReference): |
| 1195 |
|
| 1196 |
old_reference = reference |
| 1197 |
reference = FieldReference({}, dict) |
| 1198 |
visit_map[id(old_reference)] = reference |
| 1199 |
reference.set(value.to_dict(visit_map, preserve_field_references)) |
| 1200 |
else: |
| 1201 |
reference = value.to_dict(visit_map, preserve_field_references) |
| 1202 |
dict_self[key] = reference |
| 1203 |
else: |
| 1204 |
if isinstance(reference, FieldReference): |
| 1205 |
|
| 1206 |
|
| 1207 |
|
| 1208 |
|
| 1209 |
old_reference = reference |
| 1210 |
|
| 1211 |
|
| 1212 |
|
| 1213 |
reference = FieldReference(None, old_reference.get_type()) |
| 1214 |
reference.set(old_reference.get(), type_safe=False) |
| 1215 |
visit_map[id(old_reference)] = reference |
| 1216 |
dict_self[key] = reference |
| 1217 |
|
| 1218 |
return dict_self |
| 1219 |
|
| 1220 |
def copy_and_resolve_references(self, visit_map=None): |
| 1221 |
"""Returns a ConfigDict copy with FieldReferences replaced by values. |
| 1222 |
|
| 1223 |
If the object is a FrozenConfigDict, the copy returned is also a |
| 1224 |
FrozenConfigDict. However, note that FrozenConfigDict should already have |
| 1225 |
FieldReferences resolved to values, so this method effectively produces |
| 1226 |
a deep copy. |
| 1227 |
|
| 1228 |
Note: As with __eq__() and __init__(), this may not behave as expected on a |
| 1229 |
ConfigDict with self-references contained in lists, tuples, or custom types. |
| 1230 |
|
| 1231 |
Args: |
| 1232 |
visit_map: A mapping from ConfigDict object ids to their copy. Method |
| 1233 |
is recursive in nature, and it will call |
| 1234 |
".copy_and_resolve_references(visit_map)" on each encountered object, |
| 1235 |
unless it is already in visit_map. |
| 1236 |
|
| 1237 |
Returns: |
| 1238 |
ConfigDict copy with previous FieldReferences replaced by values. |
| 1239 |
""" |
| 1240 |
visit_map = visit_map or {} |
| 1241 |
config_dict_copy = self.__class__() |
| 1242 |
super(ConfigDict, config_dict_copy).__setattr__('_convert_dict', |
| 1243 |
self.convert_dict) |
| 1244 |
super(ConfigDict, config_dict_copy).__setattr__('_allow_dotted_keys', |
| 1245 |
self.allow_dotted_keys) |
| 1246 |
|
| 1247 |
visit_map[id(self)] = config_dict_copy |
| 1248 |
|
| 1249 |
for key, value in self._fields.items(): |
| 1250 |
if isinstance(value, FieldReference): |
| 1251 |
value = value.get() |
| 1252 |
|
| 1253 |
if id(value) in visit_map: |
| 1254 |
value = visit_map[id(value)] |
| 1255 |
elif isinstance(value, ConfigDict): |
| 1256 |
value = value.copy_and_resolve_references(visit_map) |
| 1257 |
|
| 1258 |
if isinstance(self, FrozenConfigDict): |
| 1259 |
config_dict_copy._frozen_setattr( |
| 1260 |
key, value) |
| 1261 |
else: |
| 1262 |
config_dict_copy[key] = value |
| 1263 |
|
| 1264 |
super(ConfigDict, config_dict_copy).__setattr__( |
| 1265 |
'_locked', self.is_locked) |
| 1266 |
super(ConfigDict, config_dict_copy).__setattr__( |
| 1267 |
'_type_safe', self.is_type_safe) |
| 1268 |
return config_dict_copy |
| 1269 |
|
| 1270 |
def __setstate__(self, state): |
| 1271 |
"""Recreates ConfigDict from its dict representation.""" |
| 1272 |
self.__init__() |
| 1273 |
super(ConfigDict, self).__setattr__('_type_safe', state['_type_safe']) |
| 1274 |
super(ConfigDict, self).__setattr__('_convert_dict', |
| 1275 |
state.get('_convert_dict', True)) |
| 1276 |
for field in state['_fields']: |
| 1277 |
self[field] = state['_fields'][field] |
| 1278 |
if state['_locked']: |
| 1279 |
|
| 1280 |
|
| 1281 |
|
| 1282 |
super(ConfigDict, self).__setattr__('_locked', True) |
| 1283 |
|
| 1284 |
@contextlib.contextmanager |
| 1285 |
def unlocked(self): |
| 1286 |
"""Context manager which temporarily unlocks a ConfigDict.""" |
| 1287 |
was_locked = self._locked |
| 1288 |
if was_locked: self.unlock() |
| 1289 |
try: |
| 1290 |
yield self |
| 1291 |
finally: |
| 1292 |
if was_locked: self.lock() |
| 1293 |
|
| 1294 |
@contextlib.contextmanager |
| 1295 |
def ignore_type(self): |
| 1296 |
"""Context manager which temporarily turns off type safety recursively.""" |
| 1297 |
original_type_safety = self._type_safe |
| 1298 |
|
| 1299 |
managers = [] |
| 1300 |
visited = set() |
| 1301 |
fields = list(self._fields.items()) |
| 1302 |
while fields: |
| 1303 |
field = fields.pop() |
| 1304 |
if id(field) in visited: |
| 1305 |
continue |
| 1306 |
|
| 1307 |
visited.add(id(field)) |
| 1308 |
if isinstance(field, ConfigDict): |
| 1309 |
managers.append(field.ignore_type) |
| 1310 |
|
| 1311 |
elif isinstance(field, collections_abc.Mapping): |
| 1312 |
fields.extend(field.items()) |
| 1313 |
elif isinstance(field, (collections_abc.Sequence, collections_abc.Set)): |
| 1314 |
fields.extend(field) |
| 1315 |
|
| 1316 |
super(ConfigDict, self).__setattr__('_type_safe', False) |
| 1317 |
try: |
| 1318 |
with contextlib.ExitStack() as stack: |
| 1319 |
for manager in managers: |
| 1320 |
stack.enter_context(manager()) |
| 1321 |
yield self |
| 1322 |
finally: |
| 1323 |
super(ConfigDict, self).__setattr__('_type_safe', original_type_safety) |
| 1324 |
|
| 1325 |
def get_type(self, key): |
| 1326 |
"""Returns type of the field associated with a key.""" |
| 1327 |
|
| 1328 |
|
| 1329 |
|
| 1330 |
|
| 1331 |
field = self.__getattr__(key) |
| 1332 |
if isinstance(self._fields[key], FieldReference): |
| 1333 |
return self._fields[key].get_type() |
| 1334 |
else: |
| 1335 |
return type(field) |
| 1336 |
|
| 1337 |
def update(self, *other, **kwargs): |
| 1338 |
"""Update values based on matching keys in another dict-like object. |
| 1339 |
|
| 1340 |
Mimics the built-in dict's update method: iterates over a given |
| 1341 |
mapping object and adds/overwrites keys with the given mapping's |
| 1342 |
values for those keys. |
| 1343 |
|
| 1344 |
Differs from dict.update in that it operates recursively on existing keys |
| 1345 |
that are already a ConfigDict (i.e. calls their update() on the |
| 1346 |
corresponding value from other), and respects the ConfigDict's |
| 1347 |
type safety status. |
| 1348 |
|
| 1349 |
If keyword arguments are specified, the ConfigDict is updated with those |
| 1350 |
key/value pairs. |
| 1351 |
|
| 1352 |
Args: |
| 1353 |
*other: A (single) dict-like container, e.g. a dict or ConfigDict. |
| 1354 |
**kwargs: Additional keyword arguments to update the ConfigDict. |
| 1355 |
|
| 1356 |
Raises: |
| 1357 |
TypeError: if more than one value for `other` is specified. |
| 1358 |
""" |
| 1359 |
if len(other) > 1: |
| 1360 |
raise TypeError( |
| 1361 |
'update expected at most 1 arguments, got {}'.format(len(other))) |
| 1362 |
for other in other + (kwargs,): |
| 1363 |
iteritems_kwargs = {} |
| 1364 |
if isinstance(other, ConfigDict): |
| 1365 |
iteritems_kwargs['preserve_field_references'] = True |
| 1366 |
|
| 1367 |
for key, value in other.items(**iteritems_kwargs): |
| 1368 |
if key not in self: |
| 1369 |
self[key] = value |
| 1370 |
elif isinstance(self._fields[key], ConfigDict): |
| 1371 |
self[key].update(other[key]) |
| 1372 |
elif (isinstance(self._fields[key], FieldReference) and |
| 1373 |
isinstance(value, FieldReference)): |
| 1374 |
|
| 1375 |
|
| 1376 |
|
| 1377 |
|
| 1378 |
|
| 1379 |
|
| 1380 |
|
| 1381 |
|
| 1382 |
|
| 1383 |
|
| 1384 |
|
| 1385 |
|
| 1386 |
|
| 1387 |
|
| 1388 |
|
| 1389 |
|
| 1390 |
|
| 1391 |
|
| 1392 |
|
| 1393 |
raise TypeError( |
| 1394 |
'Cannot update a FieldReference from another ' |
| 1395 |
f'FieldReference: {key!r}' |
| 1396 |
) |
| 1397 |
else: |
| 1398 |
self[key] = value |
| 1399 |
|
| 1400 |
def _update_value(self, key, index, value): |
| 1401 |
if index is None: |
| 1402 |
self[key] = value |
| 1403 |
elif isinstance(self[key], list): |
| 1404 |
self[key][index] = value |
| 1405 |
elif isinstance(self[key], tuple): |
| 1406 |
|
| 1407 |
tuple_as_list = list(self[key]) |
| 1408 |
tuple_as_list[index] = value |
| 1409 |
self[key] = tuple(tuple_as_list) |
| 1410 |
|
| 1411 |
def update_from_flattened_dict(self, flattened_dict, strip_prefix=''): |
| 1412 |
"""In-place updates values taken from a flattened dict. |
| 1413 |
|
| 1414 |
This allows a potentially nested source `ConfigDict` of the following form:: |
| 1415 |
|
| 1416 |
cfg = ConfigDict({ |
| 1417 |
'a': 1, |
| 1418 |
'b': { |
| 1419 |
'c': { |
| 1420 |
'd': 2 |
| 1421 |
} |
| 1422 |
} |
| 1423 |
}) |
| 1424 |
|
| 1425 |
to be updated from a dict containing paths navigating to child items, of the |
| 1426 |
following form:: |
| 1427 |
|
| 1428 |
updates = { |
| 1429 |
'a': 2, |
| 1430 |
'b.c.d': 3, |
| 1431 |
'b.c.e': 4, |
| 1432 |
} |
| 1433 |
|
| 1434 |
Note that update_from_flattened_dict will allow you add (not just update) |
| 1435 |
leaf nodes - for example, 'b.c.e' above |
| 1436 |
|
| 1437 |
This filters `paths_dict` to only contain paths starting with |
| 1438 |
`strip_prefix` and strips the prefix when applying the update. |
| 1439 |
|
| 1440 |
For example, consider we have the following values returned as flags:: |
| 1441 |
|
| 1442 |
flags = { |
| 1443 |
'flag1': x, |
| 1444 |
'flag2': y, |
| 1445 |
'config': 'some_file.py', |
| 1446 |
'config.a.b': 1, |
| 1447 |
'config.a.c': 2 |
| 1448 |
} |
| 1449 |
|
| 1450 |
config = ConfigDict({ |
| 1451 |
'a': { |
| 1452 |
'b': 0, |
| 1453 |
'c': 0 |
| 1454 |
} |
| 1455 |
}) |
| 1456 |
|
| 1457 |
config.update_from_flattened_dict(flags, 'config.') |
| 1458 |
|
| 1459 |
Then we will now have:: |
| 1460 |
|
| 1461 |
config = ConfigDict({ |
| 1462 |
'a': { |
| 1463 |
'b': 1, |
| 1464 |
'c': 2 |
| 1465 |
} |
| 1466 |
}) |
| 1467 |
|
| 1468 |
Args: |
| 1469 |
flattened_dict: A mapping (key path) -> value. |
| 1470 |
strip_prefix: A prefix to be stripped from `path`. If specified, only |
| 1471 |
paths matching `strip_prefix` will be processed. |
| 1472 |
|
| 1473 |
Raises: |
| 1474 |
KeyError: if any of the key paths can't be found. |
| 1475 |
""" |
| 1476 |
if strip_prefix: |
| 1477 |
interesting_items = { |
| 1478 |
key: value |
| 1479 |
for key, value in flattened_dict.items() |
| 1480 |
if key.startswith(strip_prefix) |
| 1481 |
} |
| 1482 |
else: |
| 1483 |
interesting_items = flattened_dict |
| 1484 |
|
| 1485 |
|
| 1486 |
|
| 1487 |
children_to_update = {} |
| 1488 |
|
| 1489 |
for full_key, value in interesting_items.items(): |
| 1490 |
key = full_key[len(strip_prefix):] if strip_prefix else full_key |
| 1491 |
|
| 1492 |
|
| 1493 |
|
| 1494 |
full_child = key.split('.')[0] |
| 1495 |
|
| 1496 |
|
| 1497 |
|
| 1498 |
|
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
|
| 1503 |
child, index = _parse_key(full_child) |
| 1504 |
|
| 1505 |
if '.' not in key and index is None: |
| 1506 |
|
| 1507 |
self[child] = value |
| 1508 |
continue |
| 1509 |
|
| 1510 |
if not child in self: |
| 1511 |
raise KeyError('Key "{}" cannot be set as "{}" was not found.' |
| 1512 |
.format(full_key, strip_prefix + child)) |
| 1513 |
|
| 1514 |
if index is not None and not isinstance(self[child], (list, tuple)): |
| 1515 |
raise KeyError('Key "{}" cannot be set as "{}" is not a tuple/list.' |
| 1516 |
.format(full_key, strip_prefix + child)) |
| 1517 |
|
| 1518 |
if '.' in key: |
| 1519 |
child_value = self[child] if index is None else self[child][index] |
| 1520 |
if not isinstance(child_value, ConfigDict): |
| 1521 |
raise KeyError( |
| 1522 |
'Key "{}" cannot be updated as "{}" is not a ConfigDict ({}).' |
| 1523 |
.format(full_key, strip_prefix + full_child, type(child_value)) |
| 1524 |
) |
| 1525 |
|
| 1526 |
children_to_update[full_child] = child_value |
| 1527 |
else: |
| 1528 |
self._update_value(child, index, value) |
| 1529 |
|
| 1530 |
for full_child, child_value in children_to_update.items(): |
| 1531 |
child_strip_prefix = f'{strip_prefix}{full_child}.' |
| 1532 |
child_value.update_from_flattened_dict( |
| 1533 |
interesting_items, child_strip_prefix |
| 1534 |
) |
| 1535 |
|
| 1536 |
|
| 1537 |
def _should_skip_type_check(old_value, new_value) -> bool: |
| 1538 |
"""Returns True if the type check should be skipped.""" |
| 1539 |
|
| 1540 |
if not isinstance(new_value, FieldReference): |
| 1541 |
return False |
| 1542 |
|
| 1543 |
|
| 1544 |
if new_value.get_type() in (type(old_value), object): |
| 1545 |
return True |
| 1546 |
else: |
| 1547 |
return False |
| 1548 |
|
| 1549 |
|
| 1550 |
def _frozenconfigdict_valid_input(obj, ancestor_list=None): |
| 1551 |
"""Raises error if obj is NOT a valid input for FrozenConfigDict. |
| 1552 |
|
| 1553 |
Args: |
| 1554 |
obj: Object to check. In the first call (with ancestor_list = None), obj |
| 1555 |
should be of type ConfigDict. During recursion, it may be any type |
| 1556 |
except dict. |
| 1557 |
ancestor_list: List of ancestors of obj in the attribute/element |
| 1558 |
structure, used to detect reference cycles in obj. |
| 1559 |
|
| 1560 |
Raises: |
| 1561 |
ValueError: If obj is an invalid input for FrozenConfigDict, i.e. if it |
| 1562 |
contains a dict within a list/tuple or contains a reference cycle. Also |
| 1563 |
if obj is a dict, which means it wasn't already converted to ConfigDict. |
| 1564 |
""" |
| 1565 |
ancestor_list = ancestor_list or [] |
| 1566 |
|
| 1567 |
|
| 1568 |
assert not isinstance(obj, dict) |
| 1569 |
|
| 1570 |
if id(obj) in ancestor_list: |
| 1571 |
raise ValueError('Bad FrozenConfigDict initialization: Cannot contain a ' |
| 1572 |
'cycle in its reference structure.') |
| 1573 |
ancestor_list.append(id(obj)) |
| 1574 |
|
| 1575 |
if isinstance(obj, ConfigDict): |
| 1576 |
for value in obj.values(): |
| 1577 |
_frozenconfigdict_valid_input(value, ancestor_list) |
| 1578 |
elif isinstance(obj, FieldReference): |
| 1579 |
_frozenconfigdict_valid_input(obj.get(), ancestor_list) |
| 1580 |
elif isinstance(obj, (list, tuple)): |
| 1581 |
for element in obj: |
| 1582 |
if isinstance(element, (dict, ConfigDict, FieldReference)): |
| 1583 |
raise ValueError('Bad FrozenConfigDict initialization: Cannot ' |
| 1584 |
'contain a dict, ConfigDict, or FieldReference ' |
| 1585 |
'within a list or tuple.') |
| 1586 |
_frozenconfigdict_valid_input(element, ancestor_list) |
| 1587 |
ancestor_list.pop() |
| 1588 |
|
| 1589 |
|
| 1590 |
def _tuple_to_immutable(value, visit_map): |
| 1591 |
"""Convert tuple to fully immutable tuple. |
| 1592 |
|
| 1593 |
Args: |
| 1594 |
value: Tuple to be made fully immutable (including its elements). |
| 1595 |
visit_map: As used elsewhere. See _frozenconfigdict_fill_seed() |
| 1596 |
documentation. Must not contain id(value) as a key (if it does, an |
| 1597 |
immutable version of value already exists). |
| 1598 |
|
| 1599 |
Returns: |
| 1600 |
immutable_value: Immutable version of value, created with minimal |
| 1601 |
copying (for example, if a value contains no mutable elements, it is |
| 1602 |
returned untouched). |
| 1603 |
same_value: Whether the same value was returned untouched, i.e. with the |
| 1604 |
same memory address. Boolean. |
| 1605 |
visit_map: Updated visit_map |
| 1606 |
|
| 1607 |
Raises: |
| 1608 |
TypeError: If one of the following: |
| 1609 |
1) value is not a tuple. |
| 1610 |
2) value contains a dict, ConfigDict, or FieldReference. If it does, |
| 1611 |
value is an invalid attribute of FrozenConfigDict, and this |
| 1612 |
should have been caught in valid_input at initialization. |
| 1613 |
ValueError: id(value) is in visit_map. |
| 1614 |
""" |
| 1615 |
|
| 1616 |
assert id(value) not in visit_map |
| 1617 |
|
| 1618 |
value_copy = [] |
| 1619 |
same_value = True |
| 1620 |
for element in value: |
| 1621 |
|
| 1622 |
assert not isinstance(element, (dict, ConfigDict, FieldReference)) |
| 1623 |
|
| 1624 |
if isinstance(element, (list, tuple, set)): |
| 1625 |
new_element, uncopied_element, visit_map = _convert_to_immutable( |
| 1626 |
element, visit_map) |
| 1627 |
same_value &= uncopied_element |
| 1628 |
value_copy.append(new_element) |
| 1629 |
else: |
| 1630 |
value_copy.append(element) |
| 1631 |
if same_value: |
| 1632 |
return value, True, visit_map |
| 1633 |
else: |
| 1634 |
return tuple(value_copy), False, visit_map |
| 1635 |
|
| 1636 |
|
| 1637 |
def _convert_to_immutable(value, visit_map): |
| 1638 |
"""Convert Python built-in type to immutable, copying if necessary. |
| 1639 |
|
| 1640 |
Args: |
| 1641 |
value: To be made immutable type (including its elements). Must have |
| 1642 |
type list, tuple, or set. |
| 1643 |
visit_map: As used elsewhere. See _frozenconfigdict_fill_seed() |
| 1644 |
documentation. |
| 1645 |
|
| 1646 |
Returns: |
| 1647 |
immutable_value: Immutable version of value, created with minimal |
| 1648 |
copying. |
| 1649 |
same_value: Whether the same value was returned untouched, i.e. with the |
| 1650 |
same memory address. Boolean. |
| 1651 |
visit_map: Updated visit_map. |
| 1652 |
|
| 1653 |
Raises: |
| 1654 |
TypeError: If value is an invalid type (not a list, tuple, or set). |
| 1655 |
""" |
| 1656 |
value_id = id(value) |
| 1657 |
if value_id in visit_map: |
| 1658 |
return visit_map[value_id], True, visit_map |
| 1659 |
|
| 1660 |
same_value = False |
| 1661 |
if isinstance(value, set): |
| 1662 |
immutable_value = frozenset(value) |
| 1663 |
elif isinstance(value, tuple): |
| 1664 |
immutable_value, same_value, visit_map = _tuple_to_immutable( |
| 1665 |
value, visit_map) |
| 1666 |
elif isinstance(value, list): |
| 1667 |
immutable_value, _, visit_map = _tuple_to_immutable(tuple(value), |
| 1668 |
visit_map) |
| 1669 |
else: |
| 1670 |
|
| 1671 |
assert False |
| 1672 |
visit_map[value_id] = immutable_value |
| 1673 |
return immutable_value, same_value, visit_map |
| 1674 |
|
| 1675 |
|
| 1676 |
def _frozenconfigdict_fill_seed(seed, initial_configdict, visit_map=None): |
| 1677 |
"""Fills an empty FrozenConfigDict without copying previously visited nodes. |
| 1678 |
|
| 1679 |
Turns seed (an empty FrozenConfigDict) into a FrozenConfigDict version of |
| 1680 |
initial_configdict. Avoids duplicating nodes of initial_configdict because if |
| 1681 |
a value of initial_configdict has been previously visited, that value is not |
| 1682 |
re-converted to a FrozenConfigDict. If a FieldReference is encountered which |
| 1683 |
contains a dict, its contents will be converted to FrozenConfigDict. |
| 1684 |
|
| 1685 |
Note: As described in the __init__() documentation, this will not |
| 1686 |
replicate the structure of initial_configdict if it contains |
| 1687 |
self-references within lists, tuples, or other types. There is no warning |
| 1688 |
or error in this case. |
| 1689 |
|
| 1690 |
Args: |
| 1691 |
seed: Empty FrozenConfigDict, to be filled in. |
| 1692 |
initial_configdict: The template on which seed is built. Must be of type |
| 1693 |
ConfigDict. |
| 1694 |
visit_map: Dictionary from memory addresses to values, storing the |
| 1695 |
FrozenConfigDict versions of dictionary values. Lists which have |
| 1696 |
been converted to tuples and sets to frozensets are also stored in |
| 1697 |
visit_map to preserve the reference structure of initial_configdict. |
| 1698 |
visit_map need not contain (id(initial_configdict), seed) as a key/value |
| 1699 |
pair. |
| 1700 |
|
| 1701 |
Raises: |
| 1702 |
ValueError: If one of the following, both of which can never happen in |
| 1703 |
practice: |
| 1704 |
1) seed is not an empty FrozenConfigDict. |
| 1705 |
2) initial_configdict contains a FieldReference. |
| 1706 |
""" |
| 1707 |
|
| 1708 |
|
| 1709 |
assert isinstance(seed, FrozenConfigDict) |
| 1710 |
assert not seed |
| 1711 |
|
| 1712 |
|
| 1713 |
|
| 1714 |
|
| 1715 |
|
| 1716 |
object.__setattr__(seed, '_configdict', initial_configdict) |
| 1717 |
|
| 1718 |
visit_map = visit_map or {} |
| 1719 |
visit_map[id(initial_configdict)] = seed |
| 1720 |
|
| 1721 |
for key, value in initial_configdict.items(): |
| 1722 |
|
| 1723 |
|
| 1724 |
if isinstance(value, FieldReference): |
| 1725 |
raise ValueError('Trying to initialize a FrozenConfigDict value with ' |
| 1726 |
'a FieldReference. This should never happen, please ' |
| 1727 |
'file a bug.') |
| 1728 |
|
| 1729 |
if id(value) in visit_map: |
| 1730 |
value = visit_map[id(value)] |
| 1731 |
elif (isinstance(value, ConfigDict) and |
| 1732 |
not isinstance(value, FrozenConfigDict)): |
| 1733 |
value_frozenconfigdict = FrozenConfigDict(type_safe=value.is_type_safe) |
| 1734 |
_frozenconfigdict_fill_seed(value_frozenconfigdict, value, visit_map) |
| 1735 |
value = value_frozenconfigdict |
| 1736 |
|
| 1737 |
seed._frozen_setattr(key, value, |
| 1738 |
visit_map) |
| 1739 |
|
| 1740 |
|
| 1741 |
class FrozenConfigDict(ConfigDict): |
| 1742 |
"""Immutable and hashable type of ConfigDict. |
| 1743 |
|
| 1744 |
See ConfigDict() documentation above for details and usage. |
| 1745 |
|
| 1746 |
FrozenConfigDict is fully immutable. It contains no lists or sets (at |
| 1747 |
initialization, lists and sets are converted to tuples and frozensets). The |
| 1748 |
only potential sources of mutability are attributes with custom types, which |
| 1749 |
are not touched. |
| 1750 |
|
| 1751 |
It is recommended to convert a ConfigDict to FrozenConfigDict after |
| 1752 |
construction if possible. |
| 1753 |
""" |
| 1754 |
|
| 1755 |
def __init__(self, initial_dictionary=None, type_safe=True): |
| 1756 |
"""Creates an instance of FrozenConfigDict. |
| 1757 |
|
| 1758 |
Lists and sets are copied into tuples and frozensets. However, copying is |
| 1759 |
kept to a minimum so tuples, frozensets, and other immutable types are not |
| 1760 |
copied unless they contain mutable types. |
| 1761 |
|
| 1762 |
Prohibited initial_dictionary structures: initial_dictionary may not contain |
| 1763 |
any lists or tuples with dictionary, ConfigDict, or FieldReference elements, |
| 1764 |
or else an error is raised at initialization. It also may not contain loops |
| 1765 |
in the reference structure, i.e. the reference structure must be a Directed |
| 1766 |
Acyclic Graph. This includes loops in list-element and tuple-element |
| 1767 |
references. initial_dictionary's reference structure need not be a tree. |
| 1768 |
|
| 1769 |
Warning: Unexpected behavior may occur with types other than Python's |
| 1770 |
built-in types. See ConfigDict() documentation for details. |
| 1771 |
|
| 1772 |
Warning: As with ConfigDict, FieldReference values may be changed. If |
| 1773 |
initial_dictionary contains a FieldReference with a value of type dict or |
| 1774 |
ConfigDict, that value will be converted to FrozenConfigDict. |
| 1775 |
|
| 1776 |
Args: |
| 1777 |
initial_dictionary: May be one of the following: |
| 1778 |
|
| 1779 |
1) dict. In this case all values of initial_dictionary that are |
| 1780 |
dictionaries are also converted to FrozenConfigDict. If there are |
| 1781 |
dictionaries contained in lists or tuples, an error is raised. |
| 1782 |
|
| 1783 |
2) ConfigDict. In this case all ConfigDict attributes are also |
| 1784 |
converted to FrozenConfigDict. |
| 1785 |
|
| 1786 |
3) FrozenConfigDict. In this case all attributes are uncopied, and |
| 1787 |
only the top-level object (self) is re-addressed. |
| 1788 |
|
| 1789 |
type_safe: See ConfigDict documentation. Note that this only matters |
| 1790 |
if the FrozenConfigDict is converted to ConfigDict at some point. |
| 1791 |
""" |
| 1792 |
|
| 1793 |
super(FrozenConfigDict, self).__init__() |
| 1794 |
|
| 1795 |
initial_configdict = ConfigDict(initial_dictionary=initial_dictionary, |
| 1796 |
type_safe=type_safe) |
| 1797 |
|
| 1798 |
_frozenconfigdict_valid_input(initial_configdict) |
| 1799 |
|
| 1800 |
_frozenconfigdict_fill_seed(self, initial_configdict) |
| 1801 |
|
| 1802 |
object.__setattr__(self, '_locked', initial_configdict.is_locked) |
| 1803 |
object.__setattr__(self, '_type_safe', initial_configdict.is_type_safe) |
| 1804 |
|
| 1805 |
def _frozen_setattr(self, key, value, visit_map=None): |
| 1806 |
"""Sets attribute, analogous to __setattr__(). |
| 1807 |
|
| 1808 |
Args: |
| 1809 |
key: Name of the attribute to set. |
| 1810 |
value: Value of the attribute to set. |
| 1811 |
visit_map: Dictionary from memory addresses to values, storing the |
| 1812 |
FrozenConfigDict versions of value's elements. Lists which have been |
| 1813 |
converted to tuples and sets to frozensets are also stored in |
| 1814 |
visit_map. |
| 1815 |
|
| 1816 |
Returns: |
| 1817 |
visit_map: Updated visit_map. |
| 1818 |
|
| 1819 |
Raises: |
| 1820 |
ValueError: If there is a dot in key, or value contains dicts inside lists |
| 1821 |
or tuples. Also if key is already an attribute, since redefining an |
| 1822 |
attribute is prohibited for FrozenConfigDict. |
| 1823 |
AttributeError: If key is protected (such as '_type_safe' and '_locked'). |
| 1824 |
""" |
| 1825 |
visit_map = visit_map or {} |
| 1826 |
|
| 1827 |
|
| 1828 |
|
| 1829 |
self._ensure_mutability(key) |
| 1830 |
assert '.' not in key |
| 1831 |
|
| 1832 |
if key in self._fields: |
| 1833 |
raise ValueError('Cannot redefine attribute of FrozenConfigDict.') |
| 1834 |
|
| 1835 |
if isinstance(value, (list, tuple, set)): |
| 1836 |
immutable_value, _, visit_map = _convert_to_immutable(value, visit_map) |
| 1837 |
self._fields[key] = immutable_value |
| 1838 |
else: |
| 1839 |
self._fields[key] = value |
| 1840 |
|
| 1841 |
return visit_map |
| 1842 |
|
| 1843 |
def __setstate__(self, state): |
| 1844 |
"""Recreates FrozenConfigDict from its dict representation.""" |
| 1845 |
self.__init__(state['_configdict']) |
| 1846 |
|
| 1847 |
def __setattr__(self, attribute, value): |
| 1848 |
raise AttributeError('FrozenConfigDict is immutable. Cannot call ' |
| 1849 |
'__setattr__().') |
| 1850 |
|
| 1851 |
def __delattr__(self, attribute): |
| 1852 |
raise AttributeError('FrozenConfigDict is immutable. Cannot call ' |
| 1853 |
'__delattr__().') |
| 1854 |
|
| 1855 |
def __setitem__(self, attribute, value): |
| 1856 |
raise AttributeError('FrozenConfigDict is immutable. Cannot call ' |
| 1857 |
'__setitem__().') |
| 1858 |
|
| 1859 |
def __delitem__(self, attribute): |
| 1860 |
raise AttributeError('FrozenConfigDict is immutable. Cannot call ' |
| 1861 |
'__delitem__().') |
| 1862 |
|
| 1863 |
def lock(self): |
| 1864 |
raise AttributeError('FrozenConfigDict is immutable. Cannot call lock().') |
| 1865 |
|
| 1866 |
def unlock(self): |
| 1867 |
raise AttributeError('FrozenConfigDict is immutable. Cannot call unlock().') |
| 1868 |
|
| 1869 |
def __hash__(self): |
| 1870 |
"""Computes hash. |
| 1871 |
|
| 1872 |
The hash depends not only on the immutable aspects of the FrozenConfigDict, |
| 1873 |
but on the types of the initial_dictionary at initialization (i.e. on the |
| 1874 |
_configdict attribute). For example, in the following, hash(frozen_1) will |
| 1875 |
not equal hash(frozen_2): |
| 1876 |
d_1 = {'a': (1, )} |
| 1877 |
d_2 = {'a': [1]} |
| 1878 |
frozen_1 = FrozenConfigDict(d_1) |
| 1879 |
frozen_2 = FrozenConfigDict(d_2) |
| 1880 |
|
| 1881 |
Note: This implementation relies on the particulars of the FrozenConfigDict |
| 1882 |
structure. For example, the fact that lists and tuples cannot contain dicts |
| 1883 |
or ConfigDicts is crucial, as is the fact that any loop in the reference |
| 1884 |
structure is prohibited. |
| 1885 |
|
| 1886 |
Note: Due to hash randomization, this hash will likely differ in different |
| 1887 |
Python sessions. For comparisons across sessions, please directly use |
| 1888 |
equality of the serialization. For more, see |
| 1889 |
https://bugs.python.org/issue13703 |
| 1890 |
|
| 1891 |
Returns: |
| 1892 |
frozenconfigdict_hash: The hash value. |
| 1893 |
|
| 1894 |
Raises: |
| 1895 |
TypeError: self contains an unhashable type. |
| 1896 |
""" |
| 1897 |
|
| 1898 |
def value_hash(value): |
| 1899 |
"""Hashes a single value.""" |
| 1900 |
if isinstance(value, set): |
| 1901 |
return hash((hash(frozenset(value)), 1)) |
| 1902 |
elif isinstance(value, (list, tuple)): |
| 1903 |
value_hash_list = [isinstance(value, list)] |
| 1904 |
for element in value: |
| 1905 |
element_hash = value_hash(element) |
| 1906 |
value_hash_list.append(element_hash) |
| 1907 |
return hash(tuple(value_hash_list)) |
| 1908 |
elif isinstance(value, FieldReference): |
| 1909 |
return value_hash(value.get()) |
| 1910 |
else: |
| 1911 |
try: |
| 1912 |
return hash(value) |
| 1913 |
except TypeError: |
| 1914 |
raise TypeError('FrozenConfigDict contains unhashable type ' |
| 1915 |
'{}'.format(type(value))) |
| 1916 |
|
| 1917 |
fields_hash = 0 |
| 1918 |
for key, value in self._fields.items(): |
| 1919 |
if isinstance(value, FrozenConfigDict): |
| 1920 |
fields_hash += hash((hash(key), hash(value))) |
| 1921 |
else: |
| 1922 |
|
| 1923 |
fields_hash += hash((hash(key), |
| 1924 |
value_hash(self._configdict._fields[key]))) |
| 1925 |
|
| 1926 |
frozenconfigdict_hash = hash((fields_hash, self.is_locked, |
| 1927 |
self.is_type_safe)) |
| 1928 |
return frozenconfigdict_hash |
| 1929 |
|
| 1930 |
def __eq__(self, other): |
| 1931 |
"""Override default Equals behavior. |
| 1932 |
|
| 1933 |
Like __hash__(), this pays attention to the type of initial_dictionary. See |
| 1934 |
__hash__() documentation for details. |
| 1935 |
|
| 1936 |
Warning: This distinguishes FrozenConfigDict from ConfigDict. For example: |
| 1937 |
cd = ConfigDict() |
| 1938 |
fcd = FrozenConfigDict() |
| 1939 |
fcd.__eq__(cd) # Returns False |
| 1940 |
|
| 1941 |
Args: |
| 1942 |
other: Object to compare self to. |
| 1943 |
|
| 1944 |
Returns: |
| 1945 |
same: Boolean self == other. |
| 1946 |
""" |
| 1947 |
if isinstance(other, FrozenConfigDict): |
| 1948 |
return ConfigDict(self) == ConfigDict(other) |
| 1949 |
else: |
| 1950 |
return False |
| 1951 |
|
| 1952 |
def as_configdict(self): |
| 1953 |
return self._configdict |
| 1954 |
|
| 1955 |
|
| 1956 |
class CustomJSONEncoder(json.JSONEncoder): |
| 1957 |
"""JSON encoder for ConfigDict and FieldReference. |
| 1958 |
|
| 1959 |
The encoder throws an exception for non-supported types. |
| 1960 |
""" |
| 1961 |
|
| 1962 |
def default(self, obj): |
| 1963 |
if isinstance(obj, FieldReference): |
| 1964 |
return obj.get() |
| 1965 |
elif isinstance(obj, ConfigDict): |
| 1966 |
return obj._fields |
| 1967 |
elif isinstance(obj, type): |
| 1968 |
return str(obj) |
| 1969 |
else: |
| 1970 |
raise TypeError('{} is not JSON serializable. Instead use ' |
| 1971 |
'ConfigDict.to_json_best_effort()'.format(type(obj))) |
| 1972 |
|
| 1973 |
|
| 1974 |
class _BestEffortCustomJSONEncoder(CustomJSONEncoder): |
| 1975 |
"""Best effort JSON encoder for ConfigDict. |
| 1976 |
|
| 1977 |
The encoder tries to serialize non-supported types (doesn't throw exceptions). |
| 1978 |
""" |
| 1979 |
|
| 1980 |
def default(self, obj): |
| 1981 |
try: |
| 1982 |
return super(_BestEffortCustomJSONEncoder, self).default(obj) |
| 1983 |
except TypeError: |
| 1984 |
if isinstance(obj, set): |
| 1985 |
return sorted(list(obj)) |
| 1986 |
elif inspect.isfunction(obj): |
| 1987 |
return 'function {}'.format(obj.__name__) |
| 1988 |
elif dataclasses.is_dataclass(obj): |
| 1989 |
return dataclasses.asdict(obj) |
| 1990 |
elif (hasattr(obj, '__dict__') and |
| 1991 |
obj.__dict__ and |
| 1992 |
not inspect.isclass(obj)): |
| 1993 |
return dict(obj.__dict__) |
| 1994 |
elif hasattr(obj, '__str__'): |
| 1995 |
return 'unserializable object: {}'.format(obj) |
| 1996 |
else: |
| 1997 |
return 'unserializable object of type: {}'.format(type(obj)) |
| 1998 |
|
| 1999 |
|
| 2000 |
def create(**kwargs): |
| 2001 |
"""Creates a `ConfigDict` with the given named arguments as key-value pairs. |
| 2002 |
|
| 2003 |
This allows for simple dictionaries whose elements can be accessed directly |
| 2004 |
using field access:: |
| 2005 |
|
| 2006 |
from ml_collections import config_dict |
| 2007 |
point = config_dict.create(x=1, y=2) |
| 2008 |
print(point.x, point.y) |
| 2009 |
|
| 2010 |
This is particularly useful for compactly writing nested configurations:: |
| 2011 |
|
| 2012 |
config = config_dict.create( |
| 2013 |
data=config_dict.create( |
| 2014 |
game='freeway', |
| 2015 |
frame_size=100), |
| 2016 |
model=config_dict.create(num_hidden=1000)) |
| 2017 |
|
| 2018 |
The reason for the existence of this function is that it simplifies the |
| 2019 |
code required for the majority of the use cases of `ConfigDict`, compared |
| 2020 |
to using either `ConfigDict` or `namedtuple's`. Examples of such use cases |
| 2021 |
include training script configuration, and returning multiple named values. |
| 2022 |
|
| 2023 |
Args: |
| 2024 |
**kwargs: key-value pairs to be stored in the `ConfigDict`. |
| 2025 |
|
| 2026 |
Returns: |
| 2027 |
A `ConfigDict` containing the key-value pairs in `kwargs`. |
| 2028 |
""" |
| 2029 |
return ConfigDict(initial_dictionary=kwargs) |
| 2030 |
|
| 2031 |
|
| 2032 |
|
| 2033 |
def placeholder(field_type, required=False): |
| 2034 |
"""Defines an entry in a ConfigDict that has no value yet. |
| 2035 |
|
| 2036 |
Example:: |
| 2037 |
|
| 2038 |
config = configdict.create( |
| 2039 |
batch_size = configdict.placeholder(int), |
| 2040 |
frame_shape = configdict.placeholder(tf.TensorShape)) |
| 2041 |
|
| 2042 |
Args: |
| 2043 |
field_type: type of value. |
| 2044 |
required: If True, the placeholder will raise an error on access if the |
| 2045 |
underlying value hasn't been set. |
| 2046 |
|
| 2047 |
Returns: |
| 2048 |
A `FieldReference` with value None and the given type. |
| 2049 |
""" |
| 2050 |
return FieldReference(None, field_type=field_type, required=required) |
| 2051 |
|
| 2052 |
|
| 2053 |
def required_placeholder(field_type): |
| 2054 |
"""Defines an entry in a ConfigDict with unknown but required value. |
| 2055 |
|
| 2056 |
Example:: |
| 2057 |
|
| 2058 |
config = configdict.create( |
| 2059 |
batch_size = configdict.required_placeholder(int)) |
| 2060 |
|
| 2061 |
try: |
| 2062 |
print(config.batch_size) |
| 2063 |
except RequiredValueError: |
| 2064 |
pass |
| 2065 |
|
| 2066 |
config.batch_size = 10 |
| 2067 |
print(config.batch_size) # 10 |
| 2068 |
|
| 2069 |
Args: |
| 2070 |
field_type: type of value. |
| 2071 |
|
| 2072 |
Returns: |
| 2073 |
A `FieldReference` with value None and the given type. |
| 2074 |
""" |
| 2075 |
return placeholder(field_type, required=True) |
| 2076 |
|
| 2077 |
|
| 2078 |
def recursive_rename(conf, old_name, new_name): |
| 2079 |
"""Returns copy of conf with old_name recursively replaced by new_name. |
| 2080 |
|
| 2081 |
This is not done in place, no changes are made to conf but a new ConfigDict is |
| 2082 |
returned with the changes made. This is useful if the name of a parameter has |
| 2083 |
been changed in code but you need to load an old config. |
| 2084 |
|
| 2085 |
Example usage: |
| 2086 |
updated_conf = configdict.recursive_rename(conf, "config", "kwargs") |
| 2087 |
|
| 2088 |
Args: |
| 2089 |
conf: a ConfigDict which needs updating |
| 2090 |
old_name: the name used in the ConfigDict which is out of sync with the code |
| 2091 |
new_name: the name used in the code |
| 2092 |
|
| 2093 |
Returns: |
| 2094 |
A ConfigDict which is a copy of conf but with all instances of old_name |
| 2095 |
replaced with new_name. |
| 2096 |
""" |
| 2097 |
new_conf = ConfigDict() |
| 2098 |
for name, c in conf.items(): |
| 2099 |
if isinstance(c, ConfigDict): |
| 2100 |
new_c = recursive_rename(c, old_name, new_name) |
| 2101 |
else: |
| 2102 |
new_c = c |
| 2103 |
if name == old_name: |
| 2104 |
setattr(new_conf, new_name, new_c) |
| 2105 |
else: |
| 2106 |
setattr(new_conf, name, new_c) |
| 2107 |
return new_conf |