Skip to content

Instantly share code, notes, and snippets.

@seanh
Created August 22, 2010 13:12
Show Gist options
  • Select an option

  • Save seanh/543749 to your computer and use it in GitHub Desktop.

Select an option

Save seanh/543749 to your computer and use it in GitHub Desktop.
Read-only attributes in Python.
In [1]: class Foo:
...: def __init__(self,x):
...: self._x = x
...: def getx(self):
...: return self._x
...: x = property(getx)
...:
...:
In [2]: f = Foo(5)
In [3]: f.x
Out[3]: 5
In [4]: f.x = 6
In [5]: f.x
Out[5]: 6
In [6]: f._x
Out[6]: 5
In [7]: class Foo(object):
...: def __init__(self,x):
...: self._x = x
...: def getx(self):
...: return self._x
...: x = property(getx)
...:
...:
In [8]: f = Foo(5)
In [9]: f.x
Out[9]: 5
In [10]: f.x = 6
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/seanh/<ipython console> in <module>()
AttributeError: can't set attribute
In [11]:
@seanh
Copy link
Copy Markdown
Author

seanh commented Aug 22, 2010

To create a read-only attribute in Python you simply use the property built-in and pass an fget parameter but not an fset. Now if user code tries to set the value of the read-only attribute AttributeError will be raised.

What confused me for ages is that for property() to work properly the class has to be a new-style class, i.e. it has to inherit from object. (I think in Python 3 maybe all classes will inherit from object implicitly, like in Java.)

In the first attempt above Foo is an old-style class, and the read-only attribute doesn't work as expected, writing the attribute produces unexpected behaviour. In the second attempt Foo inherits from object, and attempting to write the read-only attribute raises an exception.

Also see: Properties: attributes managed by get/set methods from Guido's article Unifying types and classes in Python 2.2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment