Created
September 20, 2020 16:35
-
-
Save revuel/09649eaae5608f1df401ce01a7e00f0c to your computer and use it in GitHub Desktop.
Dummy example of immutable class in python
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
""" Dumb way to produce immutable instances in Python """ | |
class ImmutablePerson(object): | |
""" ... """ | |
__slots__ = ('name', 'dob') | |
def __init__(self, name: str, dob: str): | |
""" Only available at initialization """ | |
self.name = name | |
self.dob = dob | |
def __setattr__(self, key, value): | |
""" Override to prevent mutability """ | |
if hasattr(self, key): | |
raise ValueError(f'This instance {self} is immutable: unable to change {key} with value {value}') | |
else: | |
super(ImmutablePerson, self).__setattr__(key, value) | |
@property | |
def __dict__(self): | |
return {s: getattr(self, s) for s in self.__slots__} | |
def __repr__(self): | |
return f'{self.__class__.__name__}({self.__dict__})' | |
if __name__ == '__main__': | |
p = ImmutablePerson('Michelle', '1988-03-22') | |
try: | |
p.surname = 'Macron' | |
except Exception as ex: | |
print(f'{ex}') | |
finally: | |
print(f'{p}') | |
try: | |
p.name = 'Emmanuel' | |
except Exception as ex: | |
print(f'{ex}') | |
finally: | |
print(f'{p}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment