SON data. A subclass of dict that maintains ordering of keys and provides a few extra niceties for dealing with SON. SON provides an API similar to collections.OrderedDict.
| 49 | |
| 50 | |
| 51 | class SON(Dict[_Key, _Value]): |
| 52 | """SON data. |
| 53 | |
| 54 | A subclass of dict that maintains ordering of keys and provides a |
| 55 | few extra niceties for dealing with SON. SON provides an API |
| 56 | similar to collections.OrderedDict. |
| 57 | """ |
| 58 | |
| 59 | __keys: list[Any] |
| 60 | |
| 61 | def __init__( |
| 62 | self, |
| 63 | data: Optional[Union[Mapping[_Key, _Value], Iterable[Tuple[_Key, _Value]]]] = None, |
| 64 | **kwargs: Any, |
| 65 | ) -> None: |
| 66 | self.__keys = [] |
| 67 | dict.__init__(self) |
| 68 | self.update(data) |
| 69 | self.update(kwargs) |
| 70 | |
| 71 | def __new__(cls: Type[SON[_Key, _Value]], *args: Any, **kwargs: Any) -> SON[_Key, _Value]: |
| 72 | instance = super().__new__(cls, *args, **kwargs) |
| 73 | instance.__keys = [] |
| 74 | return instance |
| 75 | |
| 76 | def __repr__(self) -> str: |
| 77 | result = [] |
| 78 | for key in self.__keys: |
| 79 | result.append(f"({key!r}, {self[key]!r})") |
| 80 | return "SON([%s])" % ", ".join(result) |
| 81 | |
| 82 | def __setitem__(self, key: _Key, value: _Value) -> None: |
| 83 | if key not in self.__keys: |
| 84 | self.__keys.append(key) |
| 85 | dict.__setitem__(self, key, value) |
| 86 | |
| 87 | def __delitem__(self, key: _Key) -> None: |
| 88 | self.__keys.remove(key) |
| 89 | dict.__delitem__(self, key) |
| 90 | |
| 91 | def copy(self) -> SON[_Key, _Value]: |
| 92 | other: SON[_Key, _Value] = SON() |
| 93 | other.update(self) |
| 94 | return other |
| 95 | |
| 96 | # TODO this is all from UserDict.DictMixin. it could probably be made more |
| 97 | # efficient. |
| 98 | # second level definitions support higher levels |
| 99 | def __iter__(self) -> Iterator[_Key]: |
| 100 | yield from self.__keys |
| 101 | |
| 102 | def has_key(self, key: _Key) -> bool: |
| 103 | warnings.warn( |
| 104 | "SON.has_key() is deprecated, use the in operator instead", |
| 105 | DeprecationWarning, |
| 106 | stacklevel=2, |
| 107 | ) |
| 108 | return key in self.__keys |
no outgoing calls