Skip to content
Snippets Groups Projects
Commit 1ad7d801 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

__slots__ for Immutable

parent d912a1a5
No related branches found
No related tags found
No related merge requests found
# v2.7.16 # v2.7.16
* extended `Proxy` * extended `Proxy`
* made `Immutable` utilize `__slots__`
\ No newline at end of file
...@@ -6,7 +6,7 @@ __all__ = ['Immutable', 'frozendict'] ...@@ -6,7 +6,7 @@ __all__ = ['Immutable', 'frozendict']
class ImmutableMetaType(ABCMeta): class ImmutableMetaType(ABCMeta):
def __call__(cls, *args, **kwargs): def __call__(cls, *args, **kwargs):
p = type.__call__(cls, *args, **kwargs) p = type.__call__(cls, *args, **kwargs)
p.__dict__['_Immutable__locked_for_writes'] = True setattr(p, '_Immutable__locked_for_writes', True)
return p return p
...@@ -21,21 +21,27 @@ class Immutable(metaclass=ImmutableMetaType): ...@@ -21,21 +21,27 @@ class Immutable(metaclass=ImmutableMetaType):
>>> self.attribute = 'value' >>> self.attribute = 'value'
""" """
__locked_for_writes = False # type: bool __slots__ = ('__locked_for_writes', )
# Following make this class immutable # Following make this class immutable
def __setattr__(self, attr, value): def __setattr__(self, attr, value):
if self.__locked_for_writes: try:
raise TypeError( if self.__locked_for_writes:
'%s does not support attribute assignment' % (self.__class__.__qualname__,)) raise TypeError(
else: '%s does not support attribute assignment' % (self.__class__.__qualname__,))
else:
super().__setattr__(attr, value)
except AttributeError:
super().__setattr__(attr, value) super().__setattr__(attr, value)
def __delattr__(self, attr): def __delattr__(self, attr):
if self.__locked_for_writes: try:
raise TypeError( if self.__locked_for_writes:
'%s does not support attribute deletion' % (self.__class__.__qualname__,)) raise TypeError(
else: '%s does not support attribute deletion' % (self.__class__.__qualname__,))
else:
super().__delattr__(attr)
except AttributeError:
super().__delattr__(attr) super().__delattr__(attr)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment