Skip to content

Instantly share code, notes, and snippets.

@revuel
Created September 20, 2020 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save revuel/09649eaae5608f1df401ce01a7e00f0c to your computer and use it in GitHub Desktop.
Save revuel/09649eaae5608f1df401ce01a7e00f0c to your computer and use it in GitHub Desktop.
Dummy example of immutable class in python
""" 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