Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Computed Property: Using @property Correctly

Learn how to implement computed properties in Python with @property: getters, setters, cached_property, and performance tradeoffs.

~6 min readPython
#python#property-decorator#oop#caching
Illustration of a Python computed property showing a getter method transforming an attribute.

Python's @property decorator lets you expose a method as an attribute. In Python, a computed property is an attribute whose value is derived from other data at runtime. Unless you add a setter, the property is read-only; you can also define a deleter. This pattern keeps validation and transformation logic in one place instead of duplicating it around the codebase. The examples below show the core syntax and the runtime behavior to expect.

The Property Decorator and Its Role in Computed Attributes

@property is implemented by Python's built-in property type. Applying it to a method lets you access that method as an attribute without parentheses. This is useful when you want to expose a value that is computed on demand rather than stored explicitly. For example, a Rectangle class might have width and height attributes and an area computed property that returns width * height. The key benefit is that area always reflects the current dimensions, even if they change after the object is created.

A computed property also encapsulates the calculation logic. If the formula changes, you update it in one place.

Basic Computed Property: Read-Only Attribute

The simplest form of a computed property is a read-only attribute. You define a method and decorate it with @property. The method takes self and returns the computed value. Here is a minimal example:

python
class Circle: def __init__(self, radius): self.radius = radius @property def diameter(self): return self.radius * 2

In this code, diameter is not stored; it is computed from radius each time you access it. If you change radius, diameter updates automatically. This is the core behavior of a computed property: the value is derived, not stored.

Because there is no setter, assigning to diameter raises an AttributeError. This is intentional; it signals that the attribute is read-only. If you need to allow assignment, you must provide a setter.

Adding Setter and Deleter Behavior

To make a computed property writable, use @property with @<property>.setter. The setter method receives the assigned value and can validate or transform it before storing it in an underlying attribute. The getter and setter must share the same method name. Here is an example:

python
class Temperature: 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("Temperature below absolute zero") self._celsius = value @property def fahrenheit(self): return self._celsius * 9 / 5 + 32 @fahrenheit.setter def fahrenheit(self, value): if value < -459.67: raise ValueError("Temperature below absolute zero") self._celsius = (value - 32) * 5 / 9

Here, celsius and fahrenheit are properties that share a single underlying attribute, _celsius. The setters enforce the same physical constraint in both units. This pattern is common when you need to expose multiple representations of the same data while keeping the internal state consistent.

You can also define a deleter with @<property>.deleter. It is called when del obj.property is executed. This is rarely needed, but it can be used to reset or remove the underlying state.

When to Use a Computed Property vs. a Regular Method

The decision between a computed property and a regular method depends on how the value is intended to be used. A computed property is appropriate when the value behaves like an attribute: it is cheap to compute, does not take arguments, and does not have side effects. For example, area or full_name are good candidates. A method is better when the operation requires arguments, performs significant work, or returns a new object that should not be mistaken for a simple attribute.

Consider a Report class that needs to generate a PDF. That operation is expensive and takes configuration options, so it should be a method like generate_pdf(format='A4'). On the other hand, page_count might be a computed property if it is derived from internal data quickly. The key is to keep the interface intuitive: if calling it with no arguments and getting a value feels like reading an attribute, use a property; if not, use a method.

Caching Computed Properties for Repeated Access

An uncached computed property recalculates its value every time it is accessed. If the underlying data rarely changes and the calculation is expensive, functools.cached_property can help. It computes the value once and stores it in the instance's __dict__; later accesses return the cached value without recomputation.

python
from functools import cached_property class DataProcessor: def __init__(self, raw_data): self.raw_data = raw_data @cached_property def processed(self): # Simulate an expensive transformation return sum(self.raw_data) / len(self.raw_data)

Here, processed is computed only on the first access. If raw_data is never modified after initialization, this is safe. If you later change the data the property depends on, the cached value becomes stale; you can delete it from the instance's __dict__ or use a regular property with manual caching. cached_property is available in Python 3.8 and later. For older versions, you can implement a simple caching mechanism with a private attribute and a check.

Performance and Runtime Cost of Computed Properties

Every access to an uncached computed property involves a method call. This is slightly slower than direct attribute access, but the difference is usually negligible unless the property is accessed in a tight loop. The real cost is the computation itself. If the calculation is heavy, caching is the appropriate optimization.

Another consideration is that computed properties can hide side effects. If a getter performs I/O or modifies state, it violates the principle of least surprise. Keep getters pure: they should only read existing state and return a derived value. This makes the property predictable and safe to call repeatedly. If you need to perform work that has side effects, use a method instead.

Common Pitfalls and Edge Cases

One common mistake is using a computed property to wrap an attribute that is already directly accessible. This adds indirection without benefit. For example, a property that simply returns self._x is unnecessary unless you need to enforce validation or a specific interface.

Another pitfall is naming conflicts. If you have a property name and an underlying attribute _name, avoid using name as the storage variable. The getter and setter must use the same method name, and the underlying attribute should have a different name, typically with a leading underscore.

Inheritance can also cause issues. If you redefine a property in a subclass with @property, you replace the entire property object, so the parent's setter is lost unless you redefine it too. To replace only the getter while keeping the existing setter, use @ParentClass.property_name.getter in the subclass.

Alternatives: getattr, getattribute, and Descriptors

Computed properties are built on the descriptor protocol. The property type is itself a descriptor. If you need more control, you can implement a custom descriptor class with __get__, __set__, and __delete__ methods. This is useful when you want to reuse the same computed logic across multiple classes or manage access at a lower level.

The __getattr__ method is another way to compute attributes dynamically. It is called only when normal attribute lookup fails. It can be used to implement computed properties, but it is less explicit and can hide bugs because it intercepts all missing attributes. __getattribute__ is called for every attribute access, which gives maximum control but also introduces more overhead and complexity. For most cases, @property is the right tool because it is explicit, readable, and easy to maintain.

When you need a settable computed property and want to share the logic, a custom descriptor is a better choice. For example, you could create a ValidatedField descriptor that validates input in multiple classes. The property decorator is sufficient for a single class, but descriptors scale better when the same behavior is needed in many places.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.