Does altering a private member decouple the property's value?

Alex Martelli aleax at
Tue Jun 19 16:15:32 CEST 2007

Ben Finney <bignose+hates-spam at> wrote:

> "Ethan Kennerly" <kennerly at> writes:
> > I really like properties for readonly attributes,
> Python doesn't have "readonly attributes", 

Many Python types do, e.g.:

>>> def f(): pass
>>> def g(): pass
>>> f.func_name = 'zap'
>>> f.func_code = g.func_code
>>> f
<function zap at 0x66070>
>>> f.func_code
<code object g at 0x55458, file "<stdin>", line 1>
>>> f.func_closure = g.func_closure
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: readonly attribute

i.e., you can reassign some of f's attributes (such as its name and
code) but others (such as its closure) are readonly (as the TypeError's
message says) so you cannot reassign those.

It makes just as much sense for user-coded types (aka classes) to have
some r/w attributes and others that are readonly, as it does for builtin
types -- and properties are often the simplest way to accomplish that.

> and to attempt to use
> properties for that purpose will only lead to confusion.

I disagree -- a property is a great way to implement readonly
attributes, as long as you're using a new-style class of course.

class Rectangle(object):

    def __init__(self, w, h):
        self.w = w
        self.h = h

    area = property(lambda self: self.w * self.h)

No confusion here -- given a Rectangle instance r, you can both read and
write (reassign) r.w and r.h, but r.area is readonly (can't be set):

>>> r = Rectangle(12, 34)
>>> r.area
>>> r.h = 10
>>> r.area
>>> r.area = 144
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute


More information about the Python-list mailing list