Sub topic 6
Making an attribute read-only
This chapter assumes you can define classes and __init__, use the @ decorator syntax, and raise and catch exceptions. It also assumes you know the @property getter from the previous chapter. You will use a getter without a setter to make an attribute read-only. You will also see what that protects against and what it does not.
Why make an attribute read-only
Some values should be fixed once an object exists. A circle's radius, a user's ID, or a timestamp recording when an object was created are examples. If outside code can overwrite them, every method that relies on them has to defend against bad changes.
Python has no final or const keyword for instance attributes. The usual tool is a property that defines only a getter. Callers can read the value with normal attribute syntax, and an assignment fails.
A property without a setter
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
c = Circle(2)
print(c.radius) # 2
try:
c.radius = 5
except AttributeError:
print("radius is read-only")The class stores the value in _radius, following the single-underscore convention for internal state. The public name radius is a property that returns it. Because no @radius.setter exists, assigning to c.radius raises AttributeError.
The exact error text depends on the Python version. Python 3.11 and later say property 'radius' of 'Circle' object has no setter. Older versions say can't set attribute. Catch the exception type and do not compare the message text.
Why the assignment fails
A property is a data descriptor, which means it defines __set__ as well as __get__. The property class always provides __set__. When no setter function was supplied, __set__ raises AttributeError. A later chapter covers descriptors in detail. For now, remember that a property takes priority over anything in the instance's __dict__.
The lookup checks the class first. This is why a read-only property cannot be bypassed by an ordinary assignment, even though the instance could otherwise hold its own radius entry.
Setting the value in `__init__`
A common mistake is to assign through the public name inside __init__:
class BrokenCircle:
def __init__(self, radius):
self.radius = radius # goes through the property, which has no setter
@property
def radius(self):
return self._radius
try:
BrokenCircle(2)
except AttributeError:
print("cannot assign to a read-only property, even in __init__")Inside the class, self.radius = radius is still an assignment to the property. Python does not exempt the class's own methods. The constructor must write to the underlying storage name, self._radius, as the Circle example does.
This differs from the validated attributes you will see in the next chapters. There, __init__ deliberately assigns through the public name so that the setter runs. A read-only attribute has no setter, so __init__ writes to the underscore name.
Deleting a read-only property
Deletion goes through the same descriptor machinery. A property without a deleter refuses del:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
c = Circle(2)
try:
del c.radius
except AttributeError:
print("cannot delete a property without a deleter")
print(c.radius) # 2You do not need to do anything extra to protect the attribute from del. A deleter is only needed when you want to allow deletion, and that is covered in a later chapter.
Read-only is a convention, not a lock
The property blocks c.radius = 5. It does not block code that reaches the storage name directly:
c = Circle(2)
c._radius = 100
print(c.radius) # 100The leading underscore tells readers not to touch _radius, but Python does not enforce it. A double underscore does not change this. It renames the attribute to _Circle__radius, which is still reachable by anyone who writes that name. The property protects against accidental or casual mutation through the public interface. It does not protect against code determined to bypass it.
That is usually the right level of protection for Python. If a team member writes c._radius = 100, the code has declared its intent, and a code review is the proper place to catch it.
The mutable value gotcha
A read-only property protects the name, not the object that the name refers to. If the getter returns a mutable object, callers can modify that object in place without ever assigning to the property:
class Playlist:
def __init__(self, tracks):
self._tracks = list(tracks)
@property
def tracks(self):
return self._tracks
p = Playlist(["intro", "verse"])
p.tracks.append("outro") # no assignment to p.tracks, so no error
print(p.tracks) # ['intro', 'verse', 'outro']The property did its job: p.tracks = [] would fail. The list inside is still open to change. You have three common ways to deal with this, depending on what you want callers to be able to do:
- Store and return an immutable type, such as a
tupleorfrozenset. - Return a copy, so changes to the copy do not affect the object's state.
- Document that the returned object is shared, and accept the risk.
class Playlist:
def __init__(self, tracks):
self._tracks = tuple(tracks)
@property
def tracks(self):
return self._tracks
def with_track(self, name):
return Playlist(self._tracks + (name,))
p = Playlist(["intro", "verse"])
q = p.with_track("outro")
print(p.tracks) # ('intro', 'verse')
print(q.tracks) # ('intro', 'verse', 'outro')
try:
p.tracks.append("x")
except AttributeError:
print("tuples have no append")Storing a tuple makes the immutability a property of the data. That is sturdier than copying on every read, and copying a large list on each access can also cost real time. If you must keep a list internally, return list(self._tracks) from the getter, and note in the docstring that the result is a copy.
Choosing a tool for read-only data
Properties are one of several ways to express "do not change this". Each fits a different situation.
| Approach | What it blocks | What it does not block | Typical use |
|---|---|---|---|
| Plain attribute with `_name` | Nothing (signals intent only) | Any assignment | Internal state that callers should not touch |
| Property with no setter | `obj.name = x` and `del obj.name` | `obj._name = x`, mutation of returned mutable objects | A public value that is set once in `__init__` or changed by methods |
| `@dataclass(frozen=True)` | Assignment to any field after creation (raises `FrozenInstanceError`, a subclass of `AttributeError`) | `object.__setattr__(obj, "field", x)`, mutation of mutable field values | Small value objects where every field is fixed |
| Immutable type such as `tuple` | In-place changes to the value itself | Rebinding the attribute that holds it | Collections that must not change |
A property without a setter is a good fit when only some attributes are fixed, or when the value is changed internally by other methods. For example, a Counter class can expose count as read-only and offer an increment() method that updates _count. Outside code can read the count but can only change it through the method you provide.
class Counter:
def __init__(self):
self._count = 0
@property
def count(self):
return self._count
def increment(self):
self._count += 1
counter = Counter()
counter.increment()
counter.increment()
print(counter.count) # 2Here "read-only" means read-only from outside the class's own interface. The class controls every change, which is the practical value of encapsulation.
Common errors
- Assigning through the public name in
__init__.self.radius = radiusraisesAttributeErrorwhenradiusis a getter-only property. Write toself._radius. - Using the same name for the property and the storage. If the getter returns
self.radius, it calls itself and recurses until Python raisesRecursionError. Store the value under a different name, normally with a leading underscore. - Expecting deep immutability. The property does not freeze the object that it returns.
- Testing the error message text. The message changed between Python versions. Test for
AttributeError. - Adding a property when nothing needs protecting. If the attribute is a plain value with no rules, a plain attribute is simpler. A later chapter covers this decision.
Exercise
A class has self.id = user_id in __init__, and you want id to be read-only afterward. A teammate changes the class to define @property def id(self): return self._id and leaves self.id = user_id in __init__. What happens when the class is instantiated, and how do you fix it?
Show answer
Creating an instance raises AttributeError, because self.id = user_id is an assignment to a property that has no setter. Fix it by changing __init__ to self._id = user_id. The getter then returns self._id, and outside code can read obj.id but cannot assign to it.
Exercise
Given class Team: def __init__(self, members): self._members = list(members) with a getter-only property members that returns self._members, does team.members.append("Ana") raise an error? Change the class so that it does not modify the team.
Show answer
It does not raise an error. The property blocks assignment to team.members, but .append() mutates the list that the getter returns. One fix is to store a tuple: self._members = tuple(members), so .append() raises AttributeError because tuples have no append. Another fix is to keep the list and return list(self._members) from the getter, so callers receive a copy.