Restricted attribute writing

Roy Smith roy at panix.com
Sun Aug 7 18:07:46 CEST 2011


In article <mailman.2010.1312731312.1164.python-list at python.org>,
 John O'Hagan <research at johnohagan.com> wrote:

> I'm looking for good ways to ensure that attributes are only writable such 
> that they retain the characteristics the class requires. 

Sounds like you're trying to do 
http://en.wikipedia.org/wiki/Design_by_contract.  Which is not a bad 
thing.  But, I think a more pythonic way to implement this would be to 
verify behaviors, not types.

I would start by writing a assert_invarient() method which validates the 
object.  I'm guessing all you really need is that you can index [0] and 
[1] and get ints, so test for that.  Something like:

def assert_invarient(self):
   try:
      assert isinstance(data[0], int)
      assert isinstance(data[1], int)
   except:
      raise ValueError

Then, call this from inside your __init__(), __setitem__(), etc.



More information about the Python-list mailing list