[Python-Dev] read-only properties
Jeff Epler
jepler@unpythonic.net
Tue, 8 Oct 2002 11:47:28 -0500
On Tue, Oct 08, 2002 at 11:37:46AM -0400, David Abrahams wrote:
[...]
> AttributeError: can't set attribute
>
> This struck me as a very poor error message, given that mechanism in
> Boost.Python v1 used to say:
[...]
> AttributeError: 'l' attribute is read-only
>
> Is it worth doing something about this?
The following comes close, in Python, but requires a setter object for
each attribute:
class SetROProperty:
def __init__(self, name):
self.name = name
def __call__(self, obj, val):
raise AttributeError, "%r attribute is read-only" % self.name
class X(object):
def get(self): return 'x'
l = property(get, SetROProperty('l'))
>>> x = X()
>>> x.l
'x'
>>> x.l = 1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "srop.py", line 5, in __call__
raise AttributeError, "%r attribute is read-only" % self.name
AttributeError: 'l' attribute is read-only
The key seems to be that property() doesn't know the name the property
has.
Jeff