Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created January 22, 2017 23:18
Show Gist options
  • Select an option

  • Save jsbueno/b2b5f5c06caa915c451253bb4f171ee9 to your computer and use it in GitHub Desktop.

Select an option

Save jsbueno/b2b5f5c06caa915c451253bb4f171ee9 to your computer and use it in GitHub Desktop.
Snippet to have abuuider for a imutable object.
class Immutable:
__slots__ = ()
def __hash__(self):
return hash(tuple(getattr(self, v) for v in self.__slots__))
def __setattr__(self, attr, value):
raise TypeError('Attributes here are imutable')
class Builder:
def __init__(self, name, **kwargs):
self._name = name
for key, value in kwargs.items():
setattr(self, key, value)
def _build(self):
class_ = type(self._name, (Immutable,),
{'__slots__': [k for k in self.__dict__.keys() if not k.startswith('_')]})
obj = class_()
for key, value in self.__dict__.items():
if key.startswith('_'): continue
object.__setattr__(obj, key, value)
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment