best practices for making read-only attributes of an object

Tim Chase python.list at tim.thechases.com
Wed Mar 15 20:19:29 CET 2006


I've set up an object and would like to make certain 
attributes read-only (or at least enforce it without doing 
extra work, as per name-mangling or the like).  Ideally, the 
property would be set in the __init__, and then not be 
allowed to change.

The best solution I've been able to come up with is 
something of the form:


class Foo:
   def __init__(self, name, value):
     self.__dict__['_name'] = name
     self.value = value
   def __getattr__(self, attr):
     name = "_%s" % attr
     if name in self.__dict__: return self.__dict__[name]
     raise AttributeError, attr
   def __setattr__(self, attr, value):
     if attr == 'value':
       self.__dict__['value'] = value
     else:
       raise AttributeError, attr

Is there a better ("more pythonic") way to do this? 
Particularly if it plays well with sub-classing Foo.

Thanks,

-tim






More information about the Python-list mailing list