2022-02-04 22:45:25 +00:00
|
|
|
"""Read only dictionary."""
|
2024-03-08 15:36:11 +00:00
|
|
|
|
2024-05-27 03:05:45 +00:00
|
|
|
from copy import deepcopy
|
2024-05-20 08:44:52 +00:00
|
|
|
from typing import Any
|
2022-02-04 22:45:25 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _readonly(*args: Any, **kwargs: Any) -> Any:
|
|
|
|
"""Raise an exception when a read only dict is modified."""
|
|
|
|
raise RuntimeError("Cannot modify ReadOnlyDict")
|
|
|
|
|
|
|
|
|
2024-05-20 08:44:52 +00:00
|
|
|
class ReadOnlyDict[_KT, _VT](dict[_KT, _VT]):
|
2022-02-04 22:45:25 +00:00
|
|
|
"""Read only version of dict that is compatible with dict types."""
|
|
|
|
|
|
|
|
__setitem__ = _readonly
|
|
|
|
__delitem__ = _readonly
|
|
|
|
pop = _readonly
|
|
|
|
popitem = _readonly
|
|
|
|
clear = _readonly
|
|
|
|
update = _readonly
|
|
|
|
setdefault = _readonly
|
2024-05-27 03:05:45 +00:00
|
|
|
|
|
|
|
def __copy__(self) -> dict[_KT, _VT]:
|
|
|
|
"""Create a shallow copy."""
|
|
|
|
return ReadOnlyDict(self)
|
|
|
|
|
|
|
|
def __deepcopy__(self, memo: Any) -> dict[_KT, _VT]:
|
|
|
|
"""Create a deep copy."""
|
|
|
|
return ReadOnlyDict(
|
|
|
|
{deepcopy(key, memo): deepcopy(value, memo) for key, value in self.items()}
|
|
|
|
)
|