Skip to content

Instantly share code, notes, and snippets.

@g4s8
Created December 2, 2015 13:21
Show Gist options
  • Save g4s8/3f43b1533b1c6836ef8a to your computer and use it in GitHub Desktop.
Save g4s8/3f43b1533b1c6836ef8a to your computer and use it in GitHub Desktop.
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