Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] - Create ImmutableDict class for .keywords. #36

Open
coltonbh opened this issue Jul 13, 2024 · 0 comments
Open

[FEATURE] - Create ImmutableDict class for .keywords. #36

coltonbh opened this issue Jul 13, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@coltonbh
Copy link
Owner

Further protection from modification of key structures. Something like this though this doesn't quite work yet:

from collections.abc import Mapping

from pydantic import BaseModel
from typing import Any, Dict, Iterator, Tuple


class ImmutableDict(Mapping):
    def __init__(self, data: Dict[str, Any]):
        self._data = dict(data)

    def __getitem__(self, key: str) -> Any:
        return self._data[key]

    def __iter__(self) -> Iterator[str]:
        return iter(self._data)

    def __len__(self) -> int:
        return len(self._data)

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}({self._data})"

    def __setitem__(self, key: str, value: Any) -> None:
        raise TypeError(f"{self.__class__.__name__} is immutable")

    def __delitem__(self, key: str) -> None:
        raise TypeError(f"{self.__class__.__name__} is immutable")

    def clear(self) -> None:
        raise TypeError(f"{self.__class__.__name__} is immutable")

    def update(self, *args, **kwargs) -> None:
        raise TypeError(f"{self.__class__.__name__} is immutable")

    def pop(self, key: str, default: Any = None) -> Any:
        raise TypeError(f"{self.__class__.__name__} is immutable")

    def popitem(self) -> Tuple[str, Any]:
        raise TypeError(f"{self.__class__.__name__} is immutable")

    def setdefault(self, key: str, default: Any = None) -> Any:
        raise TypeError(f"{self.__class__.__name__} is immutable")

    @classmethod
    def __get_pydantic_core_schema__(cls, source: type, handler: Any) -> Any:
        return handler.generate_schema(Dict[str, Any])


class _KeywordsMixin(BaseModel):
    keywords: Dict[str, Any] = {}


class _KeywordsMixinIm(BaseModel):
    keywords: ImmutableDict = {}


kw = {"a": 1, "b": 2}
mkw = _KeywordsMixin(keywords=kw)
mkw.model_dump()
print(mkw.keywords == kw)
print(mkw.keywords is kw)
mkwi = _KeywordsMixinIm(keywords=kw)
mkwi.model_dump()
print(mkwi.keywords == kw)
print(mkwi.keywords is kw)
@coltonbh coltonbh added the enhancement New feature or request label Jul 13, 2024
@coltonbh coltonbh self-assigned this Jul 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant