How should I expose read-only fields from Python classes?

I would use property as a decorator to manage your getter for name (see the example for the class Parrot in the documentation). Use, for example, something like:

class Article(object):
    def __init__(self, name, available):
        self._name = name
        self.available = available

    @property
    def name(self):
        return self._name

If you do not define the setter for the name property (using the decorator x.setter around a function) this throws an AttributeError when you try and reset name.

Note: You have to use Python’s new-style classes (i.e. in Python 2.6 you have to inherit from object) for properties to work correctly. This is not the case according to @SvenMarnach.

Leave a Comment

tech