Python property: Getters, Setters, Validation and cached_property
The Python property decorator lets an attribute run code when it is read, set or deleted, while callers still write plain obj.price. Learn getters, setters and deleters, validation that also covers __init__, read-only and computed attributes, the recursion trap, cached_property, the real speed cost, and when not to use properties, all tested.
- The Python property decorator turns a method into an attribute:
p.pricecalls a getter,p.price = 5calls a setter. - Assigning
self.price = pricein__init__runs the setter, so validation also protects object creation. - A property without a setter is read-only; our attempt to set one raised
AttributeError. - A property read took about 45 ns versus 28 ns for a plain attribute, fine for almost all code.
Java and C# developers often arrive in Python and write get_price() and set_price() methods for everything. Pythonic code starts with plain attributes instead, and only adds logic when it is needed. The Python property decorator is what makes that safe: you can later add validation, rounding or computed values behind the same attribute name, without changing a single caller.
Every example ran on Python 3.13.6 and the output is shown as printed. Properties are decorators, so our Python decorators guide is useful background.
Why properties exist
Suppose a Product class has a public price attribute used in fifty places. A new rule arrives: prices cannot be negative and must be rounded to two decimals. Without properties, you would rename the attribute, add set_price(), and update all fifty callers. With a property, you add a getter and setter under the same name, and every existing product.price read and write now goes through your rules automatically.
A getter and setter with @property
class Product:
def __init__(self, name, price):
self.name = name
self.price = price # goes through the setter
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("price cannot be negative")
self._price = round(value, 2)
p = Product("Mouse", 19.999)
print(p.price) # 20.0 (rounded by the setter)
p.price = 25
print(p.price) # 25
@property marks the getter. @price.setter attaches a setter to the same property, so both functions must use the same name. The real value lives in self._price; the leading underscore signals “internal, use the property”. Callers never see the difference.
Validation that also covers __init__
Product("Bad", -1)
# ValueError: price cannot be negative
Because __init__ assigns self.price, not self._price, the setter runs during construction too. An invalid object can never be created. Assigning to the underscore name in __init__ would skip validation, which is a subtle but common bug.
Read-only and computed properties
@property
def price_with_tax(self):
return round(self.price * 1.18, 2)
print(p.price_with_tax) # 23.6 (for a price of 20.0)
p.price_with_tax = 30
# AttributeError: property 'price_with_tax' of 'Product' object has no setter
A property with only a getter is read-only. Computed properties like this always reflect the current price, so there is no stored value to fall out of sync. Use them for derived values such as totals, full names, ages from birth dates or flags like is_overdue.
Deleters
@price.deleter
def price(self):
print(" deleting price")
del self._price
del p.price # prints " deleting price"
p.price
# AttributeError: 'Product' object has no attribute '_price'
Deleters run on del obj.attr. They are rarely needed; typical uses are clearing a cache or releasing a resource. Note the error message after deletion mentions _price, the internal name, which can confuse users of your class, one reason deleters are uncommon.
Two views of one value: unit conversion
class Temp:
def __init__(self, c):
self.celsius = c
@property
def fahrenheit(self):
return self.celsius * 9 / 5 + 32
@fahrenheit.setter
def fahrenheit(self, f):
self.celsius = (f - 32) * 5 / 9
t = Temp(100)
print(t.fahrenheit) # 212.0
t.fahrenheit = 32
print(t.celsius) # 0.0
Store one canonical value and expose others as properties with setters. Users can read and write whichever unit they think in, and there is never a mismatch between two stored numbers.
The recursion trap
class Bad:
@property
def x(self):
return self.x # calls the property again
Bad().x
# RecursionError
Inside a property, self.x means the property itself, so the getter calls itself forever. Always store the data under a different name, conventionally with a leading underscore. The same applies to setters: self.price = value inside the price setter would recurse too.
Tip: inside a property’s own getter and setter, only touch the underscore name. Everywhere else, including __init__, use the public name.
cached_property for expensive values
from functools import cached_property
class Report:
calls = 0
@cached_property
def total(self):
Report.calls += 1
time.sleep(0.05) # pretend this is a slow query
return 42
r = Report()
r.total; r.total
print(Report.calls) # 1
print("total" in r.__dict__) # True
functools.cached_property computes the value on first access and stores it in the instance dictionary, so later reads are plain attribute lookups. Our slow method ran once despite two reads. Use it for values that are expensive and do not change for the life of the object. To force a recompute, del r.total. It needs an instance __dict__, so it does not work on classes that use __slots__ without one. See our functools guide for related caching tools.
How fast are properties?
| Access (best of 3 runs, 1 million reads) | Time per read |
|---|---|
Plain attribute a.v |
27.5 ns |
Property returning self._w |
44.9 ns |
A property adds a function call, roughly 17 ns per read in our test. That is irrelevant for business logic and only worth thinking about in tight inner loops over millions of objects, where you can read the value once into a local variable.
How property works under the hood
type(Product.__dict__["price"]).__name__ # 'property'
Product.price.fset is not None # True
property is a built-in class implementing the descriptor protocol: when Python looks up p.price and finds a descriptor on the class, it calls the descriptor’s __get__ instead of returning it. The decorator syntax is shorthand for price = property(get_price, set_price, del_price, doc), with the getter, setter and deleter stored as fget, fset and fdel. Writing your own descriptor class is the next step when many attributes share the same validation logic. Our classes and objects guide covers the surrounding class machinery.
Properties with dataclasses
Dataclasses generate __init__ from fields, which makes validated attributes slightly awkward: a field and a property cannot share a name directly. The common patterns are validating in __post_init__, or using a computed property for derived values while keeping stored fields plain. For heavy validation across many fields, libraries such as pydantic are often a better fit than hand-written properties.
When not to use properties
- Slow work: attribute access looks cheap, so a property that queries a database or calls an API surprises readers. Use a method like
load_orders()instead. - Side effects: reading an attribute should not send emails or change state.
- Arguments: properties cannot take parameters; use a method.
- Nothing to add: do not wrap plain attributes in trivial getters and setters “just in case”. You can always add a property later without breaking callers.
- Exceptions: keep getters predictable; raising unexpected errors from attribute access makes debugging harder. See exception handling.
Extending a property in a subclass
class LabTemp(Temp):
@Temp.celsius.setter
def celsius(self, v):
if v > 1000: raise ValueError("sensor limit")
Temp.celsius.fset(self, v) # reuse the parent's validation
t = LabTemp(25) # 25
t.celsius = 2000 # ValueError: sensor limit
t.celsius = -300 # ValueError: below absolute zero
A subclass can add its own rule on top of the parent’s. Writing @Temp.celsius.setter takes the parent property, keeps its getter and swaps in a new setter, and Temp.celsius.fset(self, v) calls the original setter so the absolute zero check still runs. Both errors fired in our run, each from the right layer. If you used a plain @property in the subclass instead, you would replace the whole property and silently lose the parent’s getter and setter.
The property object itself is inspectable: type(Temp.celsius) printed property, Temp.celsius.fget.__name__ printed celsius, and fdel was None because we never defined a deleter. inspect.getmembers with an isinstance(v, property) filter listed every property on the class, which is handy for serialisers and admin tools that need to know which attributes are computed. For more on inheritance itself, see our Python classes and objects guide.
Final thoughts
The Python property decorator gives you the simplicity of public attributes and the safety of methods. Start with plain attributes, add a property when you need validation, normalisation or a computed value, assign through the public name in __init__ so rules always apply, and store the data under an underscore name to avoid recursion. Reach for cached_property for expensive, stable values, and for plain methods when work is slow or has side effects. Annotate property return types with type hints to keep them self-documenting.
Frequently asked questions
What does @property do in Python?
It turns a method into a managed attribute, so reading obj.name calls the method. Adding a setter with the name.setter decorator lets assignments run code as well.
How do I make a read-only attribute in Python?
Define a property with only a getter. Assigning to it raises AttributeError because the property has no setter.
Why do I get RecursionError in my property?
The getter or setter refers to its own public name, for example returning self.x inside the x property. Store the value under a different name such as self._x.
What is the difference between property and cached_property?
property runs its getter on every access. cached_property runs it once, stores the result on the instance and returns the stored value on later reads.
Are Python properties slow?
They add a function call per access. In our test a property read took about 45 nanoseconds against 28 for a plain attribute, which only matters in very tight loops.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.