Created
December 2, 2015 13:21
-
-
Save g4s8/3f43b1533b1c6836ef8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ImmutableClass(type): | |
def __new__(mcs, class_name, bases, class_dict): | |
instance = type.__new__(mcs, class_name, bases, class_dict) | |
instance.__setattr__ = ImmutableClass._setattr_impl | |
instance.__delattr__ = ImmutableClass._delattr_impl | |
return instance | |
def __call__(cls, *args, **kwargs): | |
obj = type.__call__(cls, *args, **kwargs) | |
obj.__immutable__ = True | |
return obj | |
@staticmethod | |
def _setattr_impl(self, attr, value): | |
if '__immutable__' in self.__dict__ and self.__immutable__: | |
raise AttributeError("Set not supported! '{self}' is immutable".format(self=self)) | |
else: | |
object.__setattr__(self, attr, value) | |
@staticmethod | |
def _delattr_impl(self, attr): | |
raise AttributeError("Delete not supported! '{self}' is immutable".format(self=self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment