Created
August 18, 2011 11:44
-
-
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
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
#!/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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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