commit: a4897eed2a4b77f68581ff6bfd4ef40c810b0812 Author: Brian Harring <ferringb <AT> gmail <DOT> com> AuthorDate: Fri Oct 24 17:19:30 2025 +0000 Commit: Arthur Zamarin <arthurzam <AT> gentoo <DOT> org> CommitDate: Sat Oct 25 06:18:11 2025 +0000 URL: https://gitweb.gentoo.org/proj/pkgcore/snakeoil.git/commit/?id=a4897eed
chore: typing, and deprecate ImmutableInstance in favor of metaclass Signed-off-by: Brian Harring <ferringb <AT> gmail.com> Part-of: https://github.com/pkgcore/snakeoil/pull/107 Signed-off-by: Arthur Zamarin <arthurzam <AT> gentoo.org> src/snakeoil/klass/immutable.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/snakeoil/klass/immutable.py b/src/snakeoil/klass/immutable.py index 1e28def..46e6ee2 100644 --- a/src/snakeoil/klass/immutable.py +++ b/src/snakeoil/klass/immutable.py @@ -1,17 +1,23 @@ """Implementations of immutable instance metaclasses""" __all__ = ("immutable_instance", "inject_immutable_instance", "ImmutableInstance") +import typing +import warnings +T = typing.TypeVar("T") -def _immutable_setattr(self, attr, value): + +def _immutable_setattr(self, attr: str, _value: T) -> T: raise AttributeError(self, attr) -def _immutable_delattr(self, attr): +def _immutable_delattr(self, attr: str) -> None: raise AttributeError(self, attr) -def immutable_instance(name, bases, scope, real_type=type): +def immutable_instance( + name: str, bases: tuple[type], scope: dict[str, typing.Any], real_type=type +) -> type: """metaclass that makes instances of this class effectively immutable It still is possible to do object.__setattr__ to get around it during @@ -21,7 +27,7 @@ def immutable_instance(name, bases, scope, real_type=type): return real_type(name, bases, scope) -def inject_immutable_instance(scope): +def inject_immutable_instance(scope: dict[str, typing.Any]): """inject immutable __setattr__ and __delattr__ implementations see immutable_instance for further details @@ -33,15 +39,19 @@ def inject_immutable_instance(scope): scope.setdefault("__delattr__", _immutable_delattr) [email protected]( + "snakeoil.klass.ImmutableInstance will be removed in future versions. Use the metaclasses instead" +) class ImmutableInstance: """Class that disables surface-level attribute modifications.""" __setattr__ = _immutable_setattr __delattr__ = _immutable_delattr - def __getstate__(self): + def __getstate__(self) -> dict[str, typing.Any]: return self.__dict__.copy() - def __setstate__(self, state): + def __setstate__(self, state) -> None: + # This is necessary since any mutation attempts would explode. for k, v in state.items(): object.__setattr__(self, k, v)
