Add (deep)copy support to read only dict (#118204)

This commit is contained in:
Paulus Schoutsen 2024-05-26 23:05:45 -04:00 committed by GitHub
parent 56431ef750
commit 9dc580e5de
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 14 additions and 0 deletions

View file

@ -1,5 +1,6 @@
"""Read only dictionary."""
from copy import deepcopy
from typing import Any
@ -18,3 +19,13 @@ class ReadOnlyDict[_KT, _VT](dict[_KT, _VT]):
clear = _readonly
update = _readonly
setdefault = _readonly
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()}
)

View file

@ -1,5 +1,6 @@
"""Test read only dictionary."""
import copy
import json
import pytest
@ -35,3 +36,5 @@ def test_read_only_dict() -> None:
assert isinstance(data, dict)
assert dict(data) == {"hello": "world"}
assert json.dumps(data) == json.dumps({"hello": "world"})
assert copy.deepcopy(data) == {"hello": "world"}