Properties & Descriptors
Published by Brayan K
A property is a method dressed up as an attribute: you write obj.area with no parentheses, but a function runs behind the scenes to compute it, validate it, or guard it — giving you clean attribute syntax with full control.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A computed property stays connected to its inputs
If a rectangle stores its area only when it is constructed, that saved value can become stale when its width changes. A property computes the value when it is read. Callers use ordinary attribute syntax while the class controls how the result is obtained.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
shape = Rectangle(3, 4)
print(shape.area)
shape.width = 5
print(shape.area)
print("area" in shape.__dict__)
# ✅ Expected output:
# 12
# 20
# FalseThis property does not cache the calculation or store an area entry on the instance. A read-only property also has no setter for assignments to that public name. It does not make the rest of the object immutable.
class Rectangle:
@property
def area(self):
return 12
shape = Rectangle()
shape.area = 20
# ✅ Expected error:
# AttributeError: property 'area' of 'Rectangle' object has no setterValidate both construction and later assignments through the same setter
class Stock:
def __init__(self, units):
self.units = units
@property
def units(self):
return self._units
@units.setter
def units(self, value):
if type(value) is not int or value < 0:
raise ValueError("units must be a nonnegative integer")
self._units = value
stock = Stock(3)
stock.units = 5
print(stock.units)
try:
stock.units = -1
except ValueError as error:
print(str(error))
print("Still valid:", stock.units)
# ✅ Expected output:
# 5
# units must be a nonnegative integer
# Still valid: 5The constructor assigns through the public property, so initial values follow the same rule as later updates. The setter checks before changing _units, leaving the old valid value intact on rejection. A leading underscore is a convention, not an access-control boundary; code can still deliberately bypass this property.
Assigning self.units = value inside the units setter would call the same setter again. The separate backing name prevents that recursion. Here the exact-type test deliberately excludes booleans, because treating True as one stock unit would be an unintended input policy.
class Stock:
def __init__(self, units):
self.units = units
@property
def units(self):
return self._units
@units.setter
def units(self, value):
if type(value) is not int or value < 0:
raise ValueError("units must be a nonnegative integer")
self._units = value
Stock(True)
# ✅ Expected error:
# ValueError: units must be a nonnegative integerA descriptor is shared; the values it manages usually are not
A descriptor moves managed-attribute behavior into a reusable object placed on a class. Its __get__ method handles reads and its __set__ method handles assignments. One descriptor object can serve many instances, so storing each instance’s value directly on that shared descriptor mixes their data.
class SharedValue:
def __get__(self, instance, owner=None):
if instance is None:
return self
return self.value
def __set__(self, instance, value):
self.value = value
class Item:
quantity = SharedValue()
first = Item()
second = Item()
first.quantity = 2
second.quantity = 7
print(first.quantity, second.quantity)
# ✅ Expected output:
# 7 7Both reads consult the same descriptor’s value. To keep per-instance data, store it on the instance instead. __set_name__ tells the descriptor which class attribute name it was assigned, so different fields can choose different backing names.
class Nonnegative:
def __set_name__(self, owner, name):
self.storage_name = "_" + name
def __get__(self, instance, owner=None):
if instance is None:
return self
return instance.__dict__[self.storage_name]
def __set__(self, instance, value):
if type(value) is not int or value < 0:
raise ValueError("value must be a nonnegative integer")
instance.__dict__[self.storage_name] = value
class Item:
stock = Nonnegative()
reserved = Nonnegative()
def __init__(self, stock, reserved):
self.stock = stock
self.reserved = reserved
first = Item(5, 2)
second = Item(9, 1)
first.stock = 6
print(first.stock, first.reserved)
print(second.stock, second.reserved)
print(Item.stock.storage_name)
print(Item.reserved.storage_name)
# ✅ Expected output:
# 6 2
# 9 1
# _stock
# _reservedEach field has its own descriptor object, and each Item has its own stored values. Class access such as Item.stock passes no instance, so returning self allows inspection without trying to read instance storage. This implementation expects instances with a __dict__; slotted storage has different constraints in __slots__ & Memory Optimization.
Read-only behavior depends on descriptor precedence
class Computed:
def __get__(self, instance, owner=None):
return "descriptor"
class Managed:
def __get__(self, instance, owner=None):
return "managed"
def __set__(self, instance, value):
raise AttributeError("managed value is read-only")
class Example:
computed = Computed()
managed = Managed()
item = Example()
item.__dict__["computed"] = "instance"
item.__dict__["managed"] = "instance"
print(item.computed)
print(item.managed)
# ✅ Expected output:
# instance
# managedA descriptor with __set__ or __delete__ is a data descriptor; its managed lookup takes precedence over an instance dictionary entry. A descriptor with only __get__ can be shadowed by that entry. The direct dictionary writes here expose the lookup rule; normal application code should use the public attribute interface.
Descriptor invocation comes from placing the descriptor on the class. Merely storing a descriptor object as an instance attribute does not make that value intercept the instance’s attribute access. The broader class-creation and introspection hooks belong to Metaprogramming & Introspection with inspect.
Complete a property without calling it recursively
Fill the property decorator and backing names for a label. Its getter returns the current stored text; its setter strips surrounding spaces. Construct and update through the public property so both assignments use the same transformation.
class Label:
def __init__(self, text):
self.text = text
@___
def text(self):
return self.___
@text.setter
def text(self, value):
self.___ = value.strip()
label = Label(" draft ")
print(label.text)
label.text = " ready "
print(label.text)
# 👉 replace ___ with property
# 👉 replace ___ with _text
# 👉 replace ___ with _text
# ✅ Expected output:
# draft
# readyGive two fields reusable validation without sharing their values
Create a PositiveInteger descriptor using __set_name__, __get__ and __set__. Reject booleans, non-integers and values below one with ValueError. Give a Page class separate rows and columns fields. Construct pages 3 by 4 and 2 by 5, change the first page’s rows to 6, and print both areas. Reject an attempted zero row count while retaining the first page’s valid area. Use a computed area property so it follows the current dimensions.
class PositiveInteger:
def __set_name__(self, owner, name):
self.storage_name = "_" + name
def __get__(self, instance, owner=None):
if instance is None:
return self
return instance.__dict__[self.storage_name]
def __set__(self, instance, value):
if type(value) is not int or value < 1:
raise ValueError("dimension must be a positive integer")
instance.__dict__[self.storage_name] = value
class Page:
rows = PositiveInteger()
columns = PositiveInteger()
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
@property
def area(self):
return self.rows * self.columns
first = Page(3, 4)
second = Page(2, 5)
first.rows = 6
print(first.area, second.area)
try:
first.rows = 0
except ValueError as error:
print(str(error))
print(first.area)
# ✅ Expected output:
# 24 10
# dimension must be a positive integer
# 24The calculation and validation have separate jobs. The descriptor validates each stored input, while the property derives area from those inputs. No stale area cache or shared per-page value is needed.
Practice quiz
What does this program print? class Box: def __init__(self, width): self.width = width @property def doubled(self): return self.width * 2 b = Box(3) b.width = 5 print(b.doubled)
- 10
- 6
- 5
- None
Answer: 10. The property reads the current width on access.
What does this program print? class Box: @property def size(self): return 3 b = Box() print("size" in b.__dict__) print(b.size)
- True 3
- False None
- False 3
- True None
Answer: False 3. A computed property need not store a same-named instance value.
Why should a units setter assign to _units rather than units?
- To make the value secret
- To avoid calling the same setter recursively
- To make every instance share the value
- To bypass all validation in the constructor
Answer: To avoid calling the same setter recursively. The backing attribute avoids re-entering the public property setter.
What does this program print? class Shared: def __get__(self, instance, owner=None): return self.value def __set__(self, instance, value): self.value = value class Item: amount = Shared() a, b = Item(), Item() a.amount = 2 b.amount = 9 print(a.amount, b.amount)
- 2 9
- 2 2
- 9 2
- 9 9
Answer: 9 9. The descriptor object is shared by both instances.
What does this program print? class Field: def __set_name__(self, owner, name): self.name = "_" + name class Item: count = Field() print(Item.count.name)
- count
- _count
- Item
- _Field
Answer: _count. Class creation supplies the assigned field name to __set_name__.
What does this program print? class Computed: def __get__(self, instance, owner=None): return "descriptor" class Item: value = Computed() x = Item() x.value = "instance" print(x.value)
- instance
- descriptor
- None
- AttributeError
Answer: instance. A non-data descriptor can be shadowed by an instance attribute.
Where should a descriptor keep values that must differ for each managed instance?
- Only on a shared descriptor value field
- In one global variable
- In the class name string
- In storage associated with each instance
Answer: In storage associated with each instance. The descriptor is shared; each object needs its own value storage.
What does this program print? class Managed: def __get__(self, instance, owner=None): return "managed" def __set__(self, instance, value): pass class Item: value = Managed() x = Item() x.__dict__["value"] = "instance" print(x.value)
- instance
- None
- managed
- AttributeError
Answer: managed. A data descriptor has precedence over the same-named instance entry.
Continue this course
- Previous: Abstract Base Classes (abc)
- Next: __slots__ & Memory Optimization — Cut memory and speed up attribute access by dropping __dict__
- Quick reference: Python cheat sheet
- From the blog: Object-Oriented Programming in Python