Sub topic 6
Making an attribute read-only
This chapter assumes you can define classes with __init__, use the @ decorator syntax, and catch exceptions. It also assumes you have seen a basic @property getter. Here you will use a getter alone to make an attribute read-only.
Why read-only?
Some values should be set once and never changed from outside. A circle's radius might feed other calculations, an ID should stay stable, and a timestamp records when something happened. Python does not enforce private members, so a plain attribute can always be reassigned. A property without a setter gives you a real guard: assignment fails with an error.
A getter with no setter
Define the value under a private-by-convention name such as _radius. Then expose it through a property that has only a getter.
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")Reading c.radius calls the getter. Assigning to c.radius fails because the property has no setter, so Python raises AttributeError. The same applies to del c.radius, since there is no deleter either.
What happens on assignment
The flow below shows how the two operations differ.
The property object lives on the class, not on the instance. Python finds it first when you look up or assign radius, and it handles the operation before any instance attribute could take over. That is why c.radius = 5 cannot quietly create an instance attribute that hides the getter.
Setting the value inside the class
The constructor in the example assigns self._radius directly. Assigning to self.radius would fail for the same reason it fails from outside. The private name is the place where the class itself stores the value.
Read-only means the name, not the object
The property blocks rebinding the name. It does not make the stored object immutable. If the getter returns a mutable object, callers can change its contents.
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
@property
def songs(self):
return self._songs
p = Playlist(["a", "b"])
p.songs.append("c") # allowed: the list itself is mutable
print(p.songs) # ['a', 'b', 'c']If the list must not change, return a copy or an immutable type. tuple(self._songs) returns a snapshot that callers cannot modify in place.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Assigning to a getter-only property in `__init__` (`self.radius = r`) | `AttributeError` when the object is created | Assign to `self._radius` |
| Returning a mutable object and assuming it is protected | Callers modify the contents | Return a copy or a tuple |
| Using the same name for the property and the stored value (`self.radius = ...` inside the getter) | Recursion or `AttributeError` | Store under a different name, such as `_radius` |
| Expecting the guard to stop `c._radius = 99` | The change succeeds | Treat the underscore as a convention |
When to choose this
Use a getter-only property when callers should read a value but only the class should control it. If the value never needs protection, a plain attribute is simpler. If it must change under rules, add a setter, which the next chapter covers.
Exercise
A class stores self._id = 7 and exposes id as a getter-only property. What happens when code runs obj.id = 8, and does obj._id = 8 also fail?
Show answer
obj.id = 8 raises AttributeError because the property has no setter. obj._id = 8 succeeds, because the underscore is only a convention and Python does not enforce it.
Exercise
A property returns self._items, which is a list. The property has no setter. Can a caller still add an item with obj.items.append(1)? How would you prevent it?
Show answer
Yes. The property only blocks reassigning the name, and the list stays mutable. Return tuple(self._items) or a copy so callers cannot change the stored list.