A @property turns a method into something that you read like an attribute. Pairing it with a getter and a setter is what gives you validation without changing how callers use your object. You write obj.balance instead of obj.get_balance(), but behind that syntax sits a full method that Python runs on every access. That is exactly what makes properties the right place for validation and for values that are computed.
The previous lesson in this module covered "Multiple Inheritance and the MRO", and the next lesson in this module is about "Composition vs Inheritance: Which and When".
The important thing to understand is that a property is not a special attribute. It is a descriptor, which is a class attribute that intercepts access to an instance attribute of the same name. That is why you can add validation to an assignment that already exists, in code that reads the attribute as if nothing had changed.
How do you make a read-only attribute?
Define a method, decorate it with @property, and return the value from it. The method becomes the getter, and the name that it is defined under is what you use at the call site, without any parentheses.
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def area(self):
return self._width * self._height
r = Rectangle(3, 4)
print('area:', r.area)
try:
r.area = 99
except AttributeError as error:
print('AttributeError:', error)
Trying to assign to it raises AttributeError, because there is no setter. That is a real guarantee and not a convention, since the name simply cannot be rebound from outside the class.
Notice the naming convention that is used throughout this page. The property is named area, and the underlying storage is _area, with a single leading underscore. That underscore means "private by convention". Python will not stop you from touching it, but it tells other developers that the attribute is an implementation detail.
How do you add a setter that validates?
Define a second method with the same name, decorate it with @name.setter, and do the work inside it. Python then routes every assignment to that method instead of storing the value directly.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not isinstance(value, int):
raise TypeError('age must be an int, got ' + type(value).__name__)
if value < 0 or value > 150:
raise ValueError('age ' + str(value) + ' is out of range')
self._age = value
p = Person('Asha', 30)
print(p.name, p.age)
p.age = 31
print('updated:', p.age)
try:
p.age = 200
except ValueError as error:
print('ValueError:', error)
The decorator takes its name from the function, so the method has to be called exactly age for it to attach to the age property. A getter and a setter always come as a pair, because the getter is what defines the property in the first place.
There are two details worth copying. The setter should validate before it stores anything, and it should raise a meaningful kind of error. Use ValueError for a value that has the wrong shape or is out of range, and use TypeError for a value of the wrong type. The setter should also store through the backing attribute self._age and not through self.age, because assigning to self.age inside the setter would call the setter again and recurse forever.
When should a property compute a value?
Compute it when the value is derived from other state and should not be stored at all. A full name, a price with the tax applied, and a formatted timestamp all belong in this category, because they should be worked out on demand rather than kept in step by hand.
class User:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def full_name(self):
return self.first + ' ' + self.last
@property
def initials(self):
return (self.first[0] + self.last[0]).upper()
u = User('Grace', 'Hopper')
print('full name:', u.full_name)
print('initials :', u.initials)
Computing on demand has a cost, and it shows up in a busy loop, because the body of the property runs on every read. For something like full_name that cost is nothing. For something expensive, cache the result, either in a private attribute that you refresh yourself or with functools.cached_property, which computes the value once and then stores it in the instance dictionary.
What if I already shipped a plain attribute?
This is the pattern that makes properties worth learning early. You have a class with self.price = price inside __init__, and callers read obj.price everywhere. Now you need validation. You can add a property without touching a single caller.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def show_price(product):
return product.price
legacy = Product('keyboard', 79.5)
print('the old class still works:', show_price(legacy))
class Product:
def __init__(self, name, price):
self.name = name
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if not isinstance(value, (int, float)):
raise TypeError('price must be a number, got ' + type(value).__name__)
if value < 0:
raise ValueError('price cannot be negative')
self._price = value
upgraded = Product('keyboard', 79.5)
print('the new class serves the same call:', show_price(upgraded))
upgraded.price = 60.0
print('now it validates:', upgraded.price)
try:
upgraded.price = -5
except ValueError as error:
print('ValueError:', error)
Look at the show_price function. It is written once and it works with both classes. Nothing in the calling code changed, and yet the second class now rejects bad prices. That is the whole point of a property. The public interface stays identical while the behaviour underneath becomes stricter.
The migration path is always the same. Add a property with a getter that returns the private attribute, add a setter that validates and then writes to the private attribute, and rename the old assignment in __init__ to use the private name. Every existing caller keeps working, and the new behaviour is enforced from that point on.
Is there a deleter, and what are the common patterns?
There is. @name.deleter defines what happens on del obj.name. It is rarely needed, but it completes the pattern, and it costs one decorator.
class Temp:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError('below absolute zero')
self._celsius = value
@celsius.deleter
def celsius(self):
print('clearing the reading')
del self._celsius
t = Temp(21.5)
print(t.celsius)
t.celsius = 25.0
print(t.celsius)
del t.celsius
print('the private attribute is gone:', not hasattr(t, '_celsius'))
Two patterns keep coming back. The guarded attribute keeps a private backing field and exposes a validated property, and that is what the earlier examples show. The read-only computed value exposes a derived result and offers no setter at all. A third pattern is the settable computed value, which stores nothing and simply recomputes the backing state from what you assign to it. That one works when the value has a single correct form.
There is one thing to avoid, which is using a property to hide a method that happens to be called only once. A property signals "this is a value", and callers will read it that way. If it performs work and it takes arguments, make it a plain method instead.
| You want | Write |
|---|---|
| a value that the caller reads | @property |
| a value that the caller also assigns | @property plus @name.setter |
| a value that nobody may change | @property with no setter |
| an expensive value that is used many times | @functools.cached_property |
| an action that takes arguments | a plain method |
Patterns to reuse
@propertyturns a method into an attribute-style read.- A getter with no setter is genuinely read-only, and assignment raises
AttributeError. - Add a setter with
@name.setter, validate there, and store into the private attribute. - Use properties for validation and for computed values, and not as a wrapper around ordinary work.
- Adding a property later is a safe and backwards-compatible way to introduce validation.
Try it yourself: retrofit validation onto an existing class
Start with a plain Product class that has name, price, and stock attributes set directly inside __init__. Now add a property for price that rejects negative values with ValueError and non-numeric types with TypeError. Add a read-only property named in_stock that returns a boolean.
Verify that existing code that reads product.price still works with no changes at all, and that product.price = -5 now raises an error. Then try to assign to product.in_stock and confirm that it fails. As a final step, add a discount property that accepts a percentage between 0 and 100, and expose a computed discounted_price next to it. Check that setting a discount of 150 raises the error that you wrote.