Python @property: managed attributes without getters
What you’ll learn
Section titled “What you’ll learn”- How
@property,.setterand.deleterturn methods into something callers read and assign like a plain attribute. - Why a property lives on the class and always wins over the instance
__dict__. - How to add validation to an existing public attribute without breaking a single caller.
- How properties behave under inheritance, and the bugs that bite most often (recursive setters, misnamed setters, hidden
AttributeErrors). - When to choose a plain attribute,
functools.cached_property, a method or a custom descriptor instead.
Summary
Section titled “Summary”property is a built-in class that packages a getter, an optional setter, an optional deleter and a docstring into a single class attribute. Used as a decorator, @property turns a method into a read-only attribute; @name.setter and @name.deleter add write and delete behavior. Because property is a data descriptor, every obj.name, obj.name = value and del obj.name goes through your functions. It has been part of Python since 2.2 and is fully current in Python 3.14.
The problem it solves
Section titled “The problem it solves”Python style favors plain public attributes: order.discount_rate, not order.get_discount_rate(). That is fine until a rule appears, such as “a discount may not exceed 50%”. Languages without properties push you to write getters and setters from day one; in Python you start with the attribute and switch to a property later, without touching callers.
Running the samples: each sample is a complete script. Save it as a .py file and run it with Python 3.14 (python3 sample.py). The outputs shown were produced with CPython 3.14.6; error messages differ slightly on older versions.
# Version 1 of OrdersPortal's Order: a plain public attribute.class OrderV1: def __init__(self, order_id, discount_rate=0.0): self.order_id = order_id self.discount_rate = discount_rate
order = OrderV1("ORD-1001")order.discount_rate = 1.5 # 150% off: nothing stops itprint(order.discount_rate)
# Version 2: same public name, but every write is validated.class Order: def __init__(self, order_id, discount_rate=0.0): self.order_id = order_id self.discount_rate = discount_rate # goes through the setter too
@property def discount_rate(self): """Fraction between 0 and 0.5.""" return self._discount_rate
@discount_rate.setter def discount_rate(self, value): if not 0 <= value <= 0.5: raise ValueError(f"discount_rate must be between 0 and 0.5, got {value}") self._discount_rate = value
order = Order("ORD-1001")order.discount_rate = 0.1 # callers keep the same syntaxprint(order.discount_rate)try: order.discount_rate = 1.5except ValueError as exc: print("ValueError:", exc)Output:
1.50.1ValueError: discount_rate must be between 0 and 0.5, got 1.5Note that __init__ assigns self.discount_rate, not self._discount_rate. That routes the constructor through the same validation, so no object can be born invalid. The value itself is stored in _discount_rate; the leading underscore is the convention for “internal, use the property”.
How it works
Section titled “How it works”The full signature is property(fget=None, fset=None, fdel=None, doc=None). The decorator form is shorthand for it: @property calls property(fget), and @x.setter calls a method on the existing property that returns a copy with fset filled in. That copy replaces the name in the class body, which is why every accessor must use the same function name.
class Order: def __init__(self, order_id): self._order_id = order_id
@property def order_id(self): """Public, read-only order reference.""" return self._order_id
def get_reference(self): return self._order_id
reference = property(get_reference, doc="Same thing, built without decorators.")
o = Order("ORD-1002")print(o.order_id, o.reference)
# The property object lives on the class, not the instance.prop = Order.__dict__["order_id"]print(type(prop).__name__, prop.__name__, prop.fset, Order.order_id.__doc__)
# No setter, no deleter: both fail with AttributeError.for action in ("set", "del"): try: if action == "set": o.order_id = "ORD-9999" else: del o.order_id except AttributeError as exc: print("AttributeError:", exc)
# A data descriptor beats the instance __dict__.o.__dict__["order_id"] = "sneaky"print(o.order_id, o.__dict__)
# Each decorator returns a NEW property object.class C: @property def x(self): return 1getter_only = C.__dict__["x"]with_setter = getter_only.setter(lambda self, v: None)print(getter_only is with_setter, getter_only.fset, with_setter.fset is not None)Output:
ORD-1002 ORD-1002property order_id None Public, read-only order reference.AttributeError: property 'order_id' of 'Order' object has no setterAttributeError: property 'order_id' of 'Order' object has no deleterORD-1002 {'_order_id': 'ORD-1002', 'order_id': 'sneaky'}False None TrueWhat the output shows:
- The property is a class attribute. Accessing it on the class (
Order.order_id) returns the property object itself, withfget,fset,fdel,__doc__and, since Python 3.13,__name__. - The docstring is copied from the getter unless you pass
doc, sohelp(Order)documents the attribute. - Read-only by default. Without a setter, assignment raises
AttributeError; without a deleter, so doesdel. Recent versions, including 3.14, name the property and class in the message; much older versions said onlycan't set attribute. - Data descriptors take precedence. Because
propertydefines__get__,__set__and__delete__, attribute lookup checks it before the instance dictionary. Even a value smuggled into__dict__is ignored. This is the descriptor protocol, the same machinery behind methods,classmethodandstaticmethod. - The getter runs on every read. Nothing is cached; a property is a function call that looks like an attribute.
Properties and inheritance
Section titled “Properties and inheritance”A subclass can extend a parent’s property by referring to it explicitly, but overriding only the getter silently drops the inherited setter, because the subclass defines a brand-new property object.
class Order: def __init__(self, total): self._total = total
@property def total(self): return self._total
# Extend a parent's property: reuse its getter, add a setter.class EditableOrder(Order): @Order.total.setter def total(self, value): if value < 0: raise ValueError("total cannot be negative") self._total = value
e = EditableOrder(10)e.total = 12print(e.total, Order.__dict__["total"].fset, EditableOrder.__dict__["total"].fset.__name__)
# Override only the getter: the setter is NOT inherited automatically.class TaxedOrder(EditableOrder): @property def total(self): return round(self._total * 1.2, 2)
t = TaxedOrder(10)print(t.total)try: t.total = 20except AttributeError as exc: print("AttributeError:", exc)Output:
12 None total12.0AttributeError: property 'total' of 'TaxedOrder' object has no setter@Order.total.setter copies the parent’s property, so the parent is untouched (fset is still None there). In TaxedOrder, either repeat the setter or write @EditableOrder.total.getter to keep it. For an abstract attribute, stack @property on top of @abc.abstractmethod.
Realistic example
Section titled “Realistic example”OrdersPortal’s Order exposes computed money values that must never go stale, a discount that may only change while the order is a draft, and a status that callers can read but only change through an explicit transition method.
from decimal import Decimal, ROUND_HALF_UP
CENT = Decimal("0.01")ALLOWED = {"draft": {"placed"}, "placed": {"shipped", "cancelled"}, "shipped": set(), "cancelled": set()}
class Order: """An OrdersPortal order with computed totals and guarded state."""
def __init__(self, order_id: str, lines: list[tuple[str, int, Decimal]]): self._order_id = order_id self._lines = list(lines) self._status = "draft" self.discount_rate = Decimal("0") # validated by the setter
@property def order_id(self) -> str: return self._order_id
@property def subtotal(self) -> Decimal: """Recomputed on every read, so it never goes stale.""" return sum((qty * price for _, qty, price in self._lines), Decimal("0"))
@property def discount_rate(self) -> Decimal: return self._discount_rate
@discount_rate.setter def discount_rate(self, value: Decimal) -> None: value = Decimal(value) if not Decimal("0") <= value <= Decimal("0.5"): raise ValueError(f"discount_rate out of range: {value}") if getattr(self, "_status", "draft") != "draft": raise ValueError("discount can only change while the order is a draft") self._discount_rate = value
@property def total(self) -> Decimal: discounted = self.subtotal * (1 - self.discount_rate) return discounted.quantize(CENT, rounding=ROUND_HALF_UP)
@property def status(self) -> str: return self._status # read-only: change it through transition()
def transition(self, new_status: str) -> None: if new_status not in ALLOWED[self._status]: raise ValueError(f"cannot go from {self._status} to {new_status}") self._status = new_status
def add_line(self, sku: str, qty: int, price: Decimal) -> None: self._lines.append((sku, qty, price))
order = Order("ORD-2001", [("MUG-01", 2, Decimal("8.50")), ("TEE-04", 1, Decimal("19.99"))])order.discount_rate = "0.15"print(order.subtotal, order.total)
order.add_line("PEN-02", 3, Decimal("1.20"))print(order.subtotal, order.total) # derived values follow the change
order.transition("placed")for attempt in (lambda: setattr(order, "discount_rate", "0.2"), lambda: setattr(order, "status", "shipped")): try: attempt() except (ValueError, AttributeError) as exc: print(type(exc).__name__ + ":", exc)print(order.status, order.total)Output:
36.99 31.4440.59 34.50ValueError: discount can only change while the order is a draftAttributeError: property 'status' of 'Order' object has no setterplaced 34.50subtotal and total are computed rather than stored, so adding a line cannot leave a stale total behind. The setter normalizes its input ("0.15" becomes a Decimal) and enforces a rule that depends on other state. status is read-only because a state change is an action with rules, and deserves a method name such as transition() rather than an innocent-looking assignment.
Common mistakes
Section titled “Common mistakes”# 1. The setter assigns to itself: infinite recursion.class Customer: @property def email(self): return self._email
@email.setter def email(self, value): self.email = value.lower() # should be self._email
try: Customer().email = "Ada@Example.test"except RecursionError as exc: print("RecursionError:", exc)
# 2. The setter function has a different name: two separate attributes.class Coupon: @property def code(self): return self._code
@code.setter def set_code(self, value): # creates property "set_code" self._code = value.upper()
c = Coupon()try: c.code = "save10"except AttributeError as exc: print("AttributeError:", exc)
# 3. An AttributeError inside a getter is mistaken for "attribute missing".class Shipment: def __init__(self): self.address = None
@property def city(self): return self.address.city # bug: address is None
def __getattr__(self, name): # fallback for missing attributes return f"<no {name}>"
print(Shipment().city) # the real bug is hiddenOutput:
RecursionError: maximum recursion depth exceededAttributeError: property 'code' of 'Coupon' object has no setter<no city>- Assigning to the property inside its own setter.
self.email = ...calls the setter again untilRecursionError. Store the value under a different name, conventionallyself._email. - Giving the setter a different name.
@code.setter def set_codebinds the new property toset_codeand leavescoderead-only. Every accessor must reuse the property’s name. - Letting
AttributeErrorescape a getter. When a class defines__getattr__, anAttributeErrorraised inside a property getter makes Python fall back to__getattr__, which hides the real bug. Catch it inside the getter and raise a different exception. - Bypassing validation in
__init__. Writingself._discount_rate = valuein the constructor skips the setter, so invalid objects can be created. Assign through the public name. - Doing slow or side-effecting work in a getter. Callers assume
obj.totalis cheap and repeatable. Network calls, database queries or anything that mutates state belong in a method whose name signals the cost. - Wrapping every attribute “just in case”. A property that only returns
self._xadds a function call and noise. Start with a plain attribute; you can switch later without breaking callers.
When to use it and when not to
Section titled “When to use it and when not to”Use a property when reading or writing an attribute must run code: validation, normalization, a value derived from other fields, or a read-only view of internal state. Keep it cheap, deterministic and free of visible side effects.
| Need | Best tool |
|---|---|
| Simple stored value, no rules | Plain attribute |
| Validate or normalize on assignment | @property with .setter |
| Value derived from other fields, cheap to compute | @property (no setter) |
| Expensive value computed once per immutable instance | @functools.cached_property |
| Same validation repeated across many attributes or classes | A custom descriptor with __set_name__ |
| Slow, I/O-bound or parameterized operation | A regular method (order.fetch_invoice()) |
| Class whose fields are all validated data | A dataclass with __post_init__, or a validation library |
functools.cached_property (Python 3.8) differs from property in three ways the documentation spells out: it stores the result in the instance __dict__ after the first read, it allows writes, and it needs a writable __dict__, so it does not work with __slots__ classes that omit __dict__. Since Python 3.12 it no longer holds a lock, so the getter can run more than once under concurrent first access.
Compatibility
Section titled “Compatibility”| Version | Change |
|---|---|
| 2.2 | property() built-in added with new-style classes. |
| 2.4 | Decorator syntax (@property) arrives with PEP 318. |
| 2.6 | getter, setter and deleter decorators added. |
| 3.5 | Property docstrings became writable. |
| 3.8 | functools.cached_property added. |
| 3.13 | property.__name__ attribute added. |
| 3.14 | Current release; no changes to property itself. |
Interview questions
Section titled “Interview questions”1. Why can a property not be overridden by assigning to the instance’s __dict__?
property is a data descriptor: it defines __set__ (and __delete__) as well as __get__. Attribute lookup checks data descriptors on the type before the instance dictionary, so the property always wins. Non-data descriptors such as plain functions or cached_property are checked after the instance dictionary, which is exactly how cached_property caches.
2. You change a public attribute into a property. Is that a breaking change?
For readers and writers using attribute syntax, no; that is the point of properties. It can break code that relied on the attribute being in obj.__dict__ or vars(obj), code that pickles or copies by inspecting the dictionary, and callers that assigned values the new setter now rejects. Check serializers and tests, not just call sites.
3. How do you make an attribute read-only from outside but writable inside the class?
Define a property with only a getter and store the value under an internal name (self._status). Internal code writes _status; external assignments to status raise AttributeError. Python has no access modifiers, so this is a convention plus a guard against accidental writes, not security.
4. Senior scenario: OrdersPortal’s Order.total property recalculates from 2,000 order lines and profiling shows it is called 40 times per request. What do you do?
First ask whether Order is effectively immutable after creation. If it is, functools.cached_property gives one computation per instance with no API change. If lines can change, keep total as a property but maintain the total incrementally in add_line and remove_line, or cache it and invalidate the cache in every mutating method. Do not use @property over @lru_cache on the method: the cache would hold every Order alive at class level. Also reconsider the API: if computing it is genuinely expensive, a method such as calculate_total() signals the cost to callers.
Key takeaways
Section titled “Key takeaways”@propertyruns code on attribute access while callers keepobj.namesyntax; add.setterand.deleterfor writes and deletes.- Every accessor must share the property’s name, and the setter must store the value somewhere else (
_name). - A property is a data descriptor on the class, so it beats the instance
__dict__and is not cached. - Overriding a getter in a subclass drops the inherited setter unless you rebuild it.
- Keep getters cheap and side-effect free; use
cached_propertyor methods for expensive work.
Related pages
Section titled “Related pages”- Descriptors: the protocol that
propertyis built on. - dataclasses: generated classes where properties and
__post_init__add validation. __slots__: whycached_propertyneeds a__dict__.- @staticmethod vs @classmethod: the other built-in method decorators.
- lru_cache: function-level caching and why it is risky on methods.
- Python decorators: how the
@syntax wraps functions. - Object-oriented programming: classes, attributes and inheritance.