[Python-Dev] read-only properties

Guido van Rossum guido@python.org
Tue, 08 Oct 2002 20:38:48 -0400


> Why not have the property find its name in the class's __dict__, 
> something like this:
> 
> (in class property)
>    def __set__(self, obj, value):
>      if self.fset is not None:
>        self.fset(obj, value)
>      else:
>        for key, value in type(obj).__dict__.iteritems():
>          if value is self:
>            raise AttributeError, "Property '" + key + "' is read-only."
>        # No name?  Strange put possible I guess.
>        raise AttributeError, "can't set property"

You'd have to search base classes too, in MRO order.  Doable, but
makes AttributeError very expensive.  (This can be a concern if it is
in fact being caught.)

It could also be misleading -- the same property object may occur more
than once, and you don't know which one was being set.

I think it's best to rely on the traceback.  If the traceback looks
like

    Traceback (most recent call last):
      File "foo.py", line 42, in bar
        self.foo = 42
    AttributeError: can't set attribute

the problem should be clear enough.

--Guido van Rossum (home page: http://www.python.org/~guido/)