🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Properties: Validation, Computed Fields, and Caching

Python OOPđŸŸĸ Free Lesson

Prerequisites

  • !Decorators and how @property wires a descriptor
  • !Class attributes, instance attributes, and __dict__

What You'll Learn

  • 1Explain how a property turns a method into an attribute
  • 2Put validation where it can never be bypassed
  • 3Keep derived values correct when inputs change
  • 4Cache expensive computations with awareness of the trade-offs
  • 5Recognise when a plain method or dataclass field is the better choice

A property looks like an attribute, behaves like an attribute, and is implemented as a method pair. That illusion is the point: it lets you add validation, derivation, or caching to an existing interface without renaming every call site. It is also the trap, because readers assume attribute access is cheap and side-effect free, and a property that violates either assumption quietly damages performance and testability.

How attribute access actually routes

When you write obj.radius, Python looks up radius in the instance dictionary first, then in the class, where it finds descriptors such as properties. A property bundles three hooks: a getter that runs on access, an optional setter that runs on assignment, and an optional deleter. Because the hooks are ordinary methods, everything they need can be computed, logged, or rejected right there.

python
class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("radius must be non-negative")
        self._radius = float(value)

    @property
    def area(self):
        import math
        return math.pi * self._radius ** 2

    @property
    def circumference(self):
        import math
        return 2 * math.pi * self._radius


c = Circle(5)
print(round(c.area, 2), round(c.circumference, 2))   # 78.54 31.42
c.radius = 10
print(round(c.area, 2))                              # 314.16

Notice that __init__ assigns through the property rather than touching self._radius directly. That single decision means every construction path is validated, which is the difference between a class that guarantees an invariant and one that merely hopes callers respect it. The underscore storage name marks the real field as internal, and the public name stays an attribute forever, so existing callers need no changes.

Validation that cannot be bypassed

Validation written inside setters is enforced everywhere: constructor, later assignment, and code that deserializes into the object. Validation written in a factory function only guards the paths that remember to call it, and one forgotten path is all an attacker or a typo needs.

Where validation livesConstructor pathLater assignmentExternal deserialization
Setter of a propertyEnforcedEnforcedEnforced when the key is assigned
Factory or class method onlyEnforcedNot enforcedDepends on the loader
Caller's responsibilityNever guaranteedNever guaranteedNever guaranteed
Schema library on the modelEnforcedEnforced if hookedEnforced by the library

For related fields, a plain setter on one attribute cannot see the others, and that is where the design needs a rethink. Either validate the pair in a dedicated method such as configure, or move to a dataclass with __post_init__ where the whole object is available at once. Resist the urge to reach for a metaclass to intercept assignments; by the time you are writing one, you have crossed from validation into framework design, and frameworks deserve their own module.

Derived values: recompute, or invalidate

A computed property derives its result from stored state on every access, which keeps it correct by construction but can repeat expensive work. The middle ground is to cache the derived value and invalidate it when an input changes.

python
from functools import cached_property


class Report:
    def __init__(self, rows):
        self.rows = rows
        self._revision = 0

    @property
    def revision(self):
        return self._revision

    @property
    def total(self):
        return sum(row["amount"] for row in self.rows)

    @cached_property
    def summary(self):
        print("building summary")
        by_category = {}
        for row in self.rows:
            by_category.setdefault(row["category"], 0)
            by_category[row["category"]] += row["amount"]
        return by_category

    def add_row(self, row):
        self.rows.append(row)
        self._revision += 1
        self.__dict__.pop("summary", None)


report = Report([
    {"category": "books", "amount": 30},
    {"category": "tools", "amount": 25},
])
print(report.summary)   # building summary  {'books': 30, 'tools': 25}
print(report.summary)   # cached, no extra print
report.add_row({"category": "books", "amount": 12})
print(report.summary)   # building summary  {'books': 42, 'tools': 25}

The add_row method performs the invalidation explicitly, by removing the cached entry from the instance dictionary. That is the honest version of caching: correct, obvious, and easy to get wrong when someone adds a mutation path and forgets to clear the cache. The alternative, version-tagging where the cache records the revision it was built from, tolerates forgotten invalidation because a stale cache is detected rather than returned.

What cached_property actually stores

cached_property writes the result into the instance dictionary under the property's name. Because the descriptor itself lives on the class, the first access runs the function and subsequent accesses find the plain value, which is why it costs nothing afterwards. The consequences matter for object lifecycle: the cached value is part of the instance's state, so code that copies only selected attributes may drop it, and code that iterates __dict__ will see it as data.

Pickling deserves special attention. A class whose state includes cached properties serialises those values too, which can bloat the payload or fail outright when the cached value is a lock, a connection, or a generator. Deleting the cached keys before serialising, or excluding them with a custom __getstate__, restores predictability. The same issue appears in long-lived workers where a stale cache survives a configuration change; if your cached values depend on external settings, key them on a settings version.

When a property is the wrong tool

Properties are appropriate when access should look like an attribute and the work is bounded. They are inappropriate when the work is unbounded, when the call can block, or when the caller needs to see that something expensive happened. A method named compute_summary that must be awaited or that can raise a timeout communicates far better than report.summary that silently does the same thing.

NeedBetter toolWhy
Cheap derivation from stored fieldsPropertyAttribute syntax fits the domain
Expensive, once-per-object computationcached_propertyPay once, store with the instance
Operation with parameters or side effectsMethodThe call is visible in the signature
Group of related values validated togetherDataclass with __post_init__Whole-object validation in one place
Field with schema, serialization, defaultsPydantic or attrs modelLibrary handles the plumbing

Readers also benefit from consistency. If your codebase models everything with dataclass fields, introducing properties for some classes creates two idioms to learn. Pick one primary style per module and reserve properties for the places where the extra behaviour genuinely earns its keep.

Properties as part of the storage contract

Because properties live on the class and real data usually lives under underscore names, the mapping between them is a contract you should test. Round-trip tests, assigning a value and reading it back, catch setters that normalize differently from getters. Tests that construct the object from stored fields and from its public interface catch cases where the two paths disagree.

Keep the storage name stable across refactors, since renaming _radius silently breaks any code that pokes at internals, including your own tests written in a hurry. And prefer one-way dependencies: getters may read many fields, but setters should write exactly one, which keeps invalidation reasoning local and prevents surprising cascades where setting a single attribute rewrites three others.

Debugging when the illusion breaks

Properties confuse debugging because the code you see is not the code that runs. Setting a breakpoint inside a setter that appears nowhere near the failing assignment is the classic experience, and the fix is to know where to look: assignment failures come from the setter, and read failures from the getter or from the fields they touch. Printing the instance dictionary during a failure often reveals a stale or missing underscore field, which usually means one code path wrote directly to storage while another expected the property to normalize it.

Another common confusion is a property that shadows itself by assigning to its own public name inside the setter, producing a recursion error with no obvious cause. The storage name must always differ from the property name, and a linting rule or a quick test that sets each field once will catch the mistake immediately. When a property behaves differently on a subclass, check whether the child redefined the attribute without calling the parent setter, since a plain attribute assignment in a subclass silently hides the descriptor defined above it.

Common Mistakes

Assigning to self._radius inside __init__ and skipping the setter

Fix: Assign through the public property so every construction path runs the same validation.

Caching a derived value without any invalidation strategy

Fix: Pop the cached key when an input changes, or store the revision used to build it and recompute when it differs.

Making an expensive or blocking call inside a property getter

Fix: Promote it to an explicit method whose name tells the caller that work will happen.

Assuming a property can validate several fields together

Fix: Validate pairs in a dedicated method or move to a dataclass with __post_init__ where the whole object is visible.

Best Practices

  • Route construction through properties so validation has exactly one home
  • Keep setter side effects limited to the single field being assigned
  • Use cached_property for once-per-object work and document the invalidation rule
  • Write a round-trip test for every property that normalizes input
  • Prefer dataclass fields when several values must be validated as a group

Key Takeaways

  • A property is a descriptor that routes attribute access to getter and setter methods
  • Validation in setters applies to construction, assignment, and deserialization alike
  • Computed properties stay correct automatically; cached ones need explicit invalidation
  • cached_property stores its result in the instance dictionary, affecting copying and pickling
  • Operations that are expensive, parameterised, or blocking belong in methods, not properties
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement