Skip to content

Instantly share code, notes, and snippets.

@sharat87
Created August 18, 2011 11:44
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 sharat87/1153913 to your computer and use it in GitHub Desktop.
Save sharat87/1153913 to your computer and use it in GitHub Desktop.
Immutable record like objects that just hold a bunch of data and stay immutable for the forseeable future
#!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
class ImmutabilityException(BaseException):
pass
class ImmutableRecord(object):
def __init__(self, **kwargs):
self._record = kwargs
for name, value in kwargs.items():
setattr(self, name, value)
self._immutable = True
def __setattr__(self, name, value):
if hasattr(self, '_immutable') and self._immutable:
raise ImmutabilityException('Unable to modify {name} in immutable record object'.format(name=name))
return super(ImmutableRecord, self).__setattr__(name, value)
def set(self, **kwargs):
new_record = dict(self._record)
new_record.update(kwargs)
return self.__class__(**new_record)
class Person(ImmutableRecord):
def __init__(self, name, sex):
super(Person, self).__init__(name=name, sex=sex)
def __str__(self):
return '<Person name={name} sex={sex}>'.format(name=self.name, sex=self.sex)
jack = Person(name='Jack', sex='m')
print(jack) # <Person name=Jack sex=m>
jill = jack.set(name='Jill')
print(jack) # <Person name=Jack sex=m>
print(jill) # <Person name=Jill sex=m>
@sharat87
Copy link
Author

As it turns out, I have a problem with understanding the "batteries included" philosophy of python!
http://docs.python.org/library/collections.html#collections.namedtuple

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment