|
| 1 | +# Copyright (c) Facebook, Inc. and its affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the MIT license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +import copy |
| 7 | +import json |
| 8 | +from collections.abc import MutableMapping, Mapping |
| 9 | + |
| 10 | +from .config_error import ConfigUnusedKeysError |
| 11 | + |
| 12 | + |
| 13 | +class ClassyConfigDict(MutableMapping): |
| 14 | + """Mapping which can be made immutable. Also supports tracking unused keys.""" |
| 15 | + |
| 16 | + def __init__(self, *args, **kwargs): |
| 17 | + """Create a ClassyConfigDict. |
| 18 | +
|
| 19 | + Supports the same API as a dict and recursively converts all dicts to |
| 20 | + ClassyConfigDicts. |
| 21 | + """ |
| 22 | + |
| 23 | + # NOTE: Another way to implement this would be to subclass dict, but since dict |
| 24 | + # is a built-in, it isn't treated like a regular MutableMapping, and calls like |
| 25 | + # func(**map) are handled mysteriously, probably interpreter dependent. |
| 26 | + # The downside with this implementation is that this isn't a full dict and is |
| 27 | + # just a mapping, which means some features like JSON serialization don't work |
| 28 | + |
| 29 | + self._dict = dict(*args, **kwargs) |
| 30 | + self._frozen = False |
| 31 | + self._keys_read = set() |
| 32 | + for k, v in self._dict.items(): |
| 33 | + self._dict[k] = self._from_dict(v) |
| 34 | + |
| 35 | + @classmethod |
| 36 | + def _from_dict(cls, obj): |
| 37 | + """Recursively convert all dicts inside obj to ClassyConfigDicts""" |
| 38 | + |
| 39 | + if isinstance(obj, Mapping): |
| 40 | + obj = ClassyConfigDict({k: cls._from_dict(v) for k, v in obj.items()}) |
| 41 | + elif isinstance(obj, (list, tuple)): |
| 42 | + # tuples are also converted to lists |
| 43 | + obj = [cls._from_dict(v) for v in obj] |
| 44 | + return obj |
| 45 | + |
| 46 | + def keys(self): |
| 47 | + return self._dict.keys() |
| 48 | + |
| 49 | + def items(self): |
| 50 | + self._keys_read.update(self._dict.keys()) |
| 51 | + return self._dict.items() |
| 52 | + |
| 53 | + def values(self): |
| 54 | + self._keys_read.update(self._dict.keys()) |
| 55 | + return self._dict.values() |
| 56 | + |
| 57 | + def pop(self, key, default=None): |
| 58 | + return self._dict.pop(key, default) |
| 59 | + |
| 60 | + def popitem(self): |
| 61 | + return self._dict.popitem() |
| 62 | + |
| 63 | + def clear(self): |
| 64 | + self._dict.clear() |
| 65 | + |
| 66 | + def update(self, *args, **kwargs): |
| 67 | + if self._frozen: |
| 68 | + raise TypeError("Frozen ClassyConfigDicts do not support updates") |
| 69 | + self._dict.update(*args, **kwargs) |
| 70 | + |
| 71 | + def setdefault(self, key, default=None): |
| 72 | + return self._dict.setdefault(key, default) |
| 73 | + |
| 74 | + def __contains__(self, key): |
| 75 | + return key in self._dict |
| 76 | + |
| 77 | + def __eq__(self, obj): |
| 78 | + return self._dict == obj |
| 79 | + |
| 80 | + def __len__(self): |
| 81 | + return len(self._dict) |
| 82 | + |
| 83 | + def __getitem__(self, key): |
| 84 | + self._keys_read.add(key) |
| 85 | + return self._dict.__getitem__(key) |
| 86 | + |
| 87 | + def __iter__(self): |
| 88 | + return iter(self._dict) |
| 89 | + |
| 90 | + def __str__(self): |
| 91 | + return json.dumps(self.to_dict(), indent=4) |
| 92 | + |
| 93 | + def __repr__(self): |
| 94 | + return repr(self._dict) |
| 95 | + |
| 96 | + def get(self, key, default=None): |
| 97 | + if key in self._dict.keys(): |
| 98 | + self._keys_read.add(key) |
| 99 | + return self._dict.get(key, default) |
| 100 | + |
| 101 | + def __copy__(self): |
| 102 | + ret = ClassyConfigDict() |
| 103 | + for key, value in self._dict.items(): |
| 104 | + self._keys_read.add(key) |
| 105 | + ret._dict[key] = value |
| 106 | + |
| 107 | + def copy(self): |
| 108 | + return self.__copy__() |
| 109 | + |
| 110 | + def __deepcopy__(self, memo=None): |
| 111 | + # for deepcopies we mark all the keys and sub-keys as read |
| 112 | + ret = ClassyConfigDict() |
| 113 | + for key, value in self._dict.items(): |
| 114 | + self._keys_read.add(key) |
| 115 | + ret._dict[key] = copy.deepcopy(value) |
| 116 | + return ret |
| 117 | + |
| 118 | + def __setitem__(self, key, value): |
| 119 | + if self._frozen: |
| 120 | + raise TypeError("Frozen ClassyConfigDicts do not support assignment") |
| 121 | + if isinstance(value, dict) and not isinstance(value, ClassyConfigDict): |
| 122 | + value = ClassyConfigDict(value) |
| 123 | + self._dict.__setitem__(key, value) |
| 124 | + |
| 125 | + def __delitem__(self, key): |
| 126 | + if self._frozen: |
| 127 | + raise TypeError("Frozen ClassyConfigDicts do not support key deletion") |
| 128 | + del self._dict[key] |
| 129 | + |
| 130 | + def _freeze(self, obj): |
| 131 | + if isinstance(obj, Mapping): |
| 132 | + assert isinstance(obj, ClassyConfigDict), f"{obj} is not a ClassyConfigDict" |
| 133 | + obj._frozen = True |
| 134 | + for value in obj.values(): |
| 135 | + self._freeze(value) |
| 136 | + elif isinstance(obj, list): |
| 137 | + for value in obj: |
| 138 | + self._freeze(value) |
| 139 | + |
| 140 | + def _reset_tracking(self, obj): |
| 141 | + if isinstance(obj, Mapping): |
| 142 | + assert isinstance(obj, ClassyConfigDict), f"{obj} is not a ClassyConfigDict" |
| 143 | + obj._keys_read = set() |
| 144 | + for value in obj._dict.values(): |
| 145 | + self._reset_tracking(value) |
| 146 | + elif isinstance(obj, list): |
| 147 | + for value in obj: |
| 148 | + self._reset_tracking(value) |
| 149 | + |
| 150 | + def _unused_keys(self, obj): |
| 151 | + unused_keys = [] |
| 152 | + if isinstance(obj, Mapping): |
| 153 | + assert isinstance(obj, ClassyConfigDict), f"{obj} is not a ClassyConfigDict" |
| 154 | + unused_keys = [key for key in obj._dict.keys() if key not in obj._keys_read] |
| 155 | + for key, value in obj._dict.items(): |
| 156 | + unused_keys += [ |
| 157 | + f"{key}.{subkey}" for subkey in self._unused_keys(value) |
| 158 | + ] |
| 159 | + elif isinstance(obj, list): |
| 160 | + for i, value in enumerate(obj): |
| 161 | + unused_keys += [f"{i}.{subkey}" for subkey in self._unused_keys(value)] |
| 162 | + return unused_keys |
| 163 | + |
| 164 | + def freeze(self): |
| 165 | + """Freeze the ClassyConfigDict to disallow mutations""" |
| 166 | + self._freeze(self) |
| 167 | + |
| 168 | + def reset_tracking(self): |
| 169 | + """Reset key tracking""" |
| 170 | + self._reset_tracking(self) |
| 171 | + |
| 172 | + def unused_keys(self): |
| 173 | + """Fetch all the unused keys""" |
| 174 | + return self._unused_keys(self) |
| 175 | + |
| 176 | + def check_unused_keys(self): |
| 177 | + """Raise if the config has unused keys""" |
| 178 | + unused_keys = self.unused_keys() |
| 179 | + if unused_keys: |
| 180 | + raise ConfigUnusedKeysError(unused_keys) |
0 commit comments