1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
Python property: getters, setters, validation and cached_property

Key takeaways

  • The Python property decorator turns a method into an attribute: p.price calls a getter, p.price = 5 calls a setter.
  • Assigning self.price = price in __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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Software Development

Python Abstract Class: ABC, abstractmethod and When to Use Them

Python abstract class explained: ABC and abstractmethod, abstract properties, shared logic with super, register, collections.abc and ABC vs Protocol, tested.

Read article →
Software Development

Python Subprocess Explained: run, Capture Output, Timeouts and Safety

Python subprocess explained with tested examples: run, capture_output, check, timeouts, input, environment, shell injection, encoding on Windows and Popen streaming.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters explained: reading and building them with URLSearchParams and urllib, percent encoding, plus signs, repeated keys and nine…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt explained: the 2^53 limit, creating and converting BigInt, division, mixing types, JSON stringify and parse without losing digits,…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →