Sub topic 6
Abstract properties
An abstract property declares an attribute that every concrete subclass must provide, and it can do this without fixing how the attribute is computed or stored. This chapter assumes you know the @property decorator, @abstractmethod, and what TypeError on instantiation means for an incomplete subclass. It covers the decorator order, the read-write form, what counts as an implementation, and the checks Python does not make.
Why an abstract attribute needs a property
Sometimes the contract you want is "every subclass exposes a balance", not "every subclass has a get_balance() method". Callers should write account.balance. One subclass may store the value, and another may compute it from a ledger.
A plain @abstractmethod would force callers to write account.balance(). Python has no abstract attribute declaration, such as a bare annotation that subclasses must fill in. The usual approach is to declare the attribute as an abstract property. Reading obj.balance then works for every subclass, however it implements the attribute.
Declaring a read-only abstract property
Stack @property on top and @abstractmethod directly above the def:
from abc import ABC, abstractmethod
class Account(ABC):
@property
@abstractmethod
def balance(self) -> int:
"""Current balance in cents."""
class SavingsAccount(Account):
def __init__(self, cents: int) -> None:
self._cents = cents
@property
def balance(self) -> int:
return self._cents
print(SavingsAccount(1250).balance)This prints 1250. SavingsAccount replaces the abstract balance with a concrete property of the same name, so the class is no longer abstract. Calling Account() directly raises TypeError, the same as for any other abstract method.
The decorator order matters. @abstractmethod marks the function it receives. @property then wraps the marked function, and the property reports itself as abstract because its getter is abstract.
The wrong order fails at class definition
If you reverse the decorators, @abstractmethod receives a property object. It tries to set __isabstractmethod__ on that object, and property does not allow this:
from abc import ABC, abstractmethod
try:
class Bad(ABC):
@abstractmethod
@property
def value(self) -> int:
...
except AttributeError:
print("AttributeError at class definition")This error appears when the class body runs, so you see it immediately and not later at instantiation. It is one of the few ABC mistakes that fails early.
How Python decides a property is abstract
When ABCMeta creates a class, it builds a set of names that are still abstract and stores it as __abstractmethods__. A name is abstract if the object bound to it has a true __isabstractmethod__ attribute. A property computes that attribute from its parts, and it is true if the getter, setter, or deleter is abstract.
You can inspect the result:
from abc import ABC, abstractmethod
class Account(ABC):
@property
@abstractmethod
def balance(self) -> int:
"""Current balance in cents."""
print(Account.__abstractmethods__)This prints frozenset({'balance'}). When you create a subclass, ABCMeta recomputes the set. It starts from the abstract names of the bases and keeps each name that still resolves to an abstract object on the new class. Instantiation raises TypeError if the set is not empty.
What counts as an implementation
Python checks only that the name now points to a non-abstract object. It does not check that the object is a property. This has consequences, which the next example shows:
from abc import ABC, abstractmethod
class Account(ABC):
@property
@abstractmethod
def balance(self) -> int:
"""Current balance in cents."""
class FixedAccount(Account):
balance = 500
class LazyAccount(Account):
def __init__(self) -> None:
self.balance = 5
print(FixedAccount().balance)
try:
LazyAccount()
except TypeError:
print("LazyAccount is still abstract")The output is 500 and then LazyAccount is still abstract.
- A class attribute works.
balance = 500rebinds the name to anint, which is not abstract. Readers get the value, and the contract is met. - An instance attribute does not work. The assignment in
__init__runs after the instantiation check. At class creation,balancestill resolves to the abstract property, soLazyAccount()fails before__init__runs.
If you want subclasses to set the value per instance, implement a real property that reads a private attribute, as SavingsAccount does.
Read-write abstract properties
A property can have a setter and a deleter. To require a writable attribute, mark both the getter and the setter abstract. Put @abstractmethod below the @threshold.setter line, directly above the def:
from abc import ABC, abstractmethod
class Sensor(ABC):
@property
@abstractmethod
def threshold(self) -> float:
"""Alert threshold."""
@threshold.setter
@abstractmethod
def threshold(self, value: float) -> None:
...
class Thermometer(Sensor):
def __init__(self) -> None:
self._threshold = 30.0
@property
def threshold(self) -> float:
return self._threshold
@threshold.setter
def threshold(self, value: float) -> None:
self._threshold = value
class ReadOnlyThermometer(Sensor):
@property
def threshold(self) -> float:
return 30.0
t = Thermometer()
t.threshold = 35.0
print(t.threshold)
r = ReadOnlyThermometer()
print("created a ReadOnlyThermometer")
try:
r.threshold = 10.0
except AttributeError:
print("AttributeError: no setter")The output is:
35.0
created a ReadOnlyThermometer
AttributeError: no setterReadOnlyThermometer instantiates without complaint, even though the base class declared a setter. The subclass's threshold is a new property with no abstract parts, so ABCMeta sees an implemented name. It does not compare the shape of the subclass property with the base property, so it cannot tell that the setter is missing.
If you need every subclass to be writable, the abstract setter does not guarantee it. Test for it, or enforce it with a type checker. A type checker does treat a read-only property as incompatible with a read-write one.
Giving an abstract property a default body
An abstract property may contain real code. Subclasses must still override it, but they can call the base version with super():
from abc import ABC, abstractmethod
class Report(ABC):
@property
@abstractmethod
def title(self) -> str:
return "Report"
class SalesReport(Report):
@property
def title(self) -> str:
return f"Sales {super().title}"
print(SalesReport().title)This prints Sales Report. Use it when there is a sensible shared part, such as a prefix or a default value, and you still want each subclass to take a decision about it.
Using abstract properties in a template method
An abstract property can feed concrete methods, as area() fed describe() in the Shape example earlier. The base class reads the property and never needs to know how the subclass computes it:
from abc import ABC, abstractmethod
class Account(ABC):
@property
@abstractmethod
def balance(self) -> int:
"""Current balance in cents."""
def statement(self) -> str:
dollars, cents = divmod(self.balance, 100)
return f"Balance: ${dollars}.{cents:02d}"
class SavingsAccount(Account):
def __init__(self, cents: int) -> None:
self._cents = cents
@property
def balance(self) -> int:
return self._cents
print(SavingsAccount(1250).statement())This prints Balance: $12.50. A subclass could compute balance by summing a list of transactions, and statement() would work unchanged.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `AttributeError` when the class body runs | `@abstractmethod` placed above `@property` | Put `@property` first, then `@abstractmethod` directly above the `def` |
| `TypeError` on instantiation although `__init__` assigns the attribute | The instance attribute is set after the abstract check runs | Define a property, or a class attribute, on the subclass |
| Subclass instantiates but assigning raises `AttributeError` | Base declared an abstract setter, subclass defined a getter only | Add a setter in the subclass. The ABC does not check for it |
| Subclass instantiates but `obj.name` is a bound method | Subclass implemented the name as a plain method | Use a type checker, or add a test that reads the attribute |
| Only the getter is marked abstract, and the subclass overrides only the getter | The setter was never declared abstract | Mark the setter `@abstractmethod` as well |
Exercises
Exercise
This class is meant to require a name attribute. What happens when it is defined, and how do you fix it?
class Animal(ABC):
@abstractmethod
@property
def name(self) -> str:
...
Show answer
Defining the class raises AttributeError, because @abstractmethod receives a property object and cannot set _isabstractmethod_ on it. Swap the order so @property is on top and @abstractmethod sits directly above the def.
Exercise
Given the correct Animal base class with an abstract name property, a subclass Dog sets self.name = "Rex" inside _init_ and defines no name property. What happens on Dog(), and why?
Show answer
Dog() raises TypeError. ABCMeta computes the abstract names when the class is created, and name still resolves to the inherited abstract property then. The assignment in _init_ would only run later, after the instantiation check has already failed. Define a name property or a class attribute name = "Rex" on Dog instead.
Exercise
A base class declares an abstract getter and an abstract setter for threshold. A subclass defines only a getter for threshold. Does Python raise an error at instantiation? What happens when code assigns to the attribute?
Show answer
No error at instantiation, because the subclass's threshold is a new non-abstract property and ABCMeta does not compare property shapes. Assigning to it raises AttributeError because that property has no setter.