Saturday, October 10, 2009

Freezing Objects in Python

Someone stop me. I like freezing simple objects or what Eric Evans calls "Value Objects" in his excellent "Domain Driven Design" book. Python doesn't have immutable objects (ala freeze in Ruby) explicitly, but we can easily create it. Python gives us the power to get under its covers. Here's my implementation:
class ValueObject(object):
def __setattr__(self, name, value):
if name == 'value' and hasattr(self, 'value'):
raise AttributeError("Can not change value attribute")
self.__dict__[name] = value

Do you have to ask? Yes, I made a test. Here they are:
import unittest
class Test(unittest.TestCase):

def testSimple(self):
class Cents(ValueObject):
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value) + " cents"
subject = Cents(5)
self.assertEquals(5, subject.value)
def set_value():
subject.value = 6
self.failUnlessRaises(AttributeError, set_value)

No comments: