Created
January 22, 2017 23:18
-
-
Save jsbueno/b2b5f5c06caa915c451253bb4f171ee9 to your computer and use it in GitHub Desktop.
Snippet to have abuuider for a imutable object.
This file contains hidden or 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 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