Python OOP: Abstract Classes, Metaclasses, slots
Python's object model has four levels of leverage, and most code uses the wrong one. __slots__ changes how instances store attributes, descriptors change how attribute access behaves, abstract base classes change what can be instantiated, and metaclasses change how classes themselves are created. Each is powerful, and each is easy to misuse: slots break subclassing assumptions, a naive descriptor silently loses its state, and a metaclass applied to one class makes an entire hierarchy harder to read. This lesson takes them in ascending order of leverage, with the concrete cost and the concrete payoff for each.
What You'll Learn
- 1Define abstract interfaces with ABC and know when duck typing is enough
- 2Measure and justify __slots__ in memory-sensitive classes
- 3Implement descriptors with __set_name__ and understand property as sugar
- 4Decide whether a metaclass, a decorator, or a class factory is the right tool
Abstract base classes as enforced contracts
An abstract base class declares which methods a subclass must provide and refuses to be instantiated until they exist. Unlike a NotImplementedError raised at call time, the failure happens at instantiation â earlier, louder, and with a clear list of what is missing. ABCs also let you provide shared concrete methods alongside the abstract ones, so a family of classes can implement a small protocol while inheriting real logic.
The design question is how much to put in the base. Keep abstract methods minimal and behaviour-rich helpers concrete, and document the contract each abstract method must satisfy â returning a sorted list versus an arbitrary one is a difference that no signature can express. Over-specifying with many abstract methods makes every subclass a rewrite; under-specifying produces classes that technically conform and behave inconsistently.
from abc import ABC, abstractmethod
class Exporter(ABC):
@abstractmethod
def export(self, rows):
"""Return rows encoded for this format."""
@abstractmethod
def content_type(self):
...
def export_all(self, batches):
return [self.export(batch) for batch in batches]
class CsvExporter(Exporter):
def export(self, rows):
header = ",".join(rows[0])
body = "\n".join(",".join(str(v) for v in row) for row in rows)
return header + "\n" + body
def content_type(self):
return "text/csv"
try:
Exporter()
except TypeError as exc:
print("blocked:", exc)
csv = CsvExporter()
print(csv.content_type()) # text/csv
print(csv.export_all([ [("a", "b"), ("1", "2")] ]) [0].splitlines())
# ['a,b', '1,2']
Notice that export_all was inherited untouched â the concrete part of an ABC is ordinary code. Python also supports runtime-checkable protocols through typing, which validate structure after the fact rather than blocking construction; protocols fit duck-typed libraries, while ABCs fit hierarchies you control and want to constrain.
Slots: trading flexibility for memory
Every normal instance carries a dictionary for its attributes, which costs memory per object and a dictionary lookup per access. Declaring __slots__ replaces that dictionary with fixed descriptors for the named attributes: memory drops substantially for millions of instances, attribute access gets slightly faster, and accidental attributes become impossible â assigning an undeclared name raises AttributeError instead of silently expanding the object.
The costs are real. Slots prevent adding attributes not listed, make multiple inheritance with another slotted class complicated, and stop subclasses from gaining a dictionary unless they declare one themselves. Pickling and debugging tools behave differently too, since there is no __dict__ to inspect. The rule of thumb: use slots for data-carrying records instantiated in large numbers, and skip them for base classes, configuration objects, and anything whose attributes legitimately evolve.
import sys
from dataclasses import dataclass
class Plain:
def __init__(self, sku, qty):
self.sku = sku
self.qty = qty
class Slotted:
__slots__ = ("sku", "qty")
def __init__(self, sku, qty):
self.sku = sku
self.qty = qty
plain = Plain("a", 1)
slotted = Slotted("a", 1)
print(sys.getsizeof(plain.__dict__), sys.getsizeof(slotted)) # e.g. 64 48
try:
slotted.location = "shelf-3"
except AttributeError as exc:
print("rejected:", exc)
@dataclass(slots=True)
class Row:
sku: str
qty: int
print(Row("b", 2)) # dataclass builds the slots for you
sys.getsizeof on the instance plus its __dict__ gives a fair comparison, though the true saving includes the shared attribute values as well. When the record count is in the millions, measure with tracemalloc on a representative batch rather than trusting a single object's size.
Descriptors and attribute access
A descriptor is any object with __get__, __set__, or __delete__ that lives as a class attribute and intercepts access through it. property is the built-in read-only descriptor most Python code uses, but writing one by hand shows the protocol: __get__ receives the instance and its class, __set__ receives the value, and __set_name__ â added in Python 3.6 â hands the descriptor its attribute name at class creation so one class can manage several fields.
That last hook is what removes the boilerplate that used to require one descriptor instance per field. Validation, unit conversion, lazy computation, and attribute change notifications all fit the pattern. The trap is storage: the descriptor needs somewhere to keep the value that is not the attribute it intercepts, and the usual answer is a private name in the instance's dictionary â which, notably, interacts badly with __slots__ unless that private name is declared too.
class Validated:
def __init__(self, low, high, label=None):
self.low = low
self.high = high
self.label = label
def __set_name__(self, owner, name):
self.label = self.label or name
self.private = "_" + name
def __get__(self, instance, owner=None):
if instance is None:
return self
return getattr(instance, self.private, None)
def __set__(self, instance, value):
if not (self.low <= value <= self.high):
raise ValueError(f"{self.label} must be between {self.low} and {self.high}")
setattr(instance, self.private, value)
class Sensor:
humidity = Validated(0, 100)
pressure = Validated(800, 1200, label="pressure hPa")
def __init__(self, humidity, pressure):
self.humidity = humidity
self.pressure = pressure
s = Sensor(45, 1013)
print(s.humidity) # 45
print(Sensor.humidity) # the descriptor itself when accessed on the class
try:
s.humidity = 250
except ValueError as exc:
print("rejected:", exc)
Reading the attribute on the class returns the descriptor rather than a value â the if instance is None branch â which is exactly how classmethod and staticmethod behave. Getting that branch wrong is the most common descriptor bug, and it produces errors that look unrelated to the descriptor at all.
Metaclasses: when class creation is the problem
A metaclass is the class of a class: type is the default, and a custom metaclass gets to run when a class statement is executed. Its hooks â __new__ and __init__ receive the class name, bases, and namespace â let you register subclasses automatically, validate that abstract methods were implemented, inject fields, or enforce coding rules across a hierarchy. When you need every class in a framework to behave consistently, a metaclass is the only hook that runs at definition time for all of them.
Metaclasses are also the tool most often reached for prematurely. A decorator applied to individual classes, a base class with __init_subclass__, or a plain class factory function accomplishes most goals with less magic and no effect on unrelated classes. __init_subclass__, added in Python 3.6, is the first thing to try: it runs when a subclass is defined, receives the subclass, and keeps the normal class machinery intact.
class Registry(type):
_registry = {}
def __new__(mcls, name, bases, namespace):
cls = super().__new__(mcls, name, bases, namespace)
if bases:
Registry._registry[name] = cls
return cls
@classmethod
def get(mcls, name):
return mcls._registry.get(name)
class Handler(metaclass=Registry):
def handle(self, payload):
raise NotImplementedError
class EmailHandler(Handler):
def handle(self, payload):
return f"email:{payload}"
class SmsHandler(Handler):
def handle(self, payload):
return f"sms:{payload}"
print(sorted(Registry._registry)) # ['EmailHandler', 'SmsHandler']
print(Registry.get("SmsHandler")().handle(9)) # sms:9
# The __init_subclass__ equivalent, without a metaclass
class Plugin:
_registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
Plugin._registry[cls.__name__] = cls
class A(Plugin): pass
class B(Plugin): pass
print(sorted(Plugin._registry)) # ['A', 'B']
The two versions register identically, but the metaclass version intercepts every class statement under Registry, including ones you did not write, while __init_subclass__ affects only descendants of Plugin. Choose the narrower mechanism unless you genuinely control all classes in the system.
Dataclasses: the everyday alternative
Before reaching for any of the machinery above, check whether a dataclass already answers the need. Dataclasses generate __init__, __repr__, and __eq__ from annotations, and frozen=True gives immutable instances whose hash comes from their fields. Validation fits through __post_init__, which runs after field assignment and can raise before the object escapes. That combination covers most of what people build descriptors and metaclasses for, at a fraction of the reading cost.
The remaining gaps are exactly where the heavier tools earn their place: computed attributes that respond to access rather than construction, invariants that must hold on every assignment rather than only at creation, and rules that must apply across many classes at definition time. Recognising that boundary keeps the specialisation rare, which is what makes it readable when it does appear.
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Money:
amount: float
currency: str = "USD"
tags: tuple = field(default=())
def __post_init__(self):
if self.amount != self.amount:
raise ValueError("amount is not a number")
if len(self.currency) != 3:
raise ValueError("currency must be a three-letter code")
def convert(self, rate, currency):
return Money(round(self.amount * rate, 2), currency, self.tags)
total = Money(19.99)
print(total) # Money(amount=19.99, currency='USD', tags=())
print(hash(total) is not None, total == Money(19.99)) # True True
try:
Money(1.5, "US")
except ValueError as exc:
print("rejected:", exc)
print(total.convert(0.92, "EUR")) # Money(amount=18.39, currency='EUR', tags=())
Two details are worth internalising. frozen=True makes the instance hashable but only because assignment is blocked â mutating a field after creation raises FrozenInstanceError, which is what lets instances sit in sets and serve as dictionary keys. And mutable defaults such as lists are rejected outright by dataclasses, forcing field(default_factory=list) so every instance gets its own collection instead of sharing one.
Choosing an interface style
Four mechanisms express "implement this contract", and they differ in when they check, how strictly, and at what cost to readability. Picking by habit produces code that validates too late or constrains too much.
| Mechanism | Checked when | Strictness | Best for |
|---|---|---|---|
| Duck typing | At call time | None | Small scripts and protocols nobody formalises |
typing.Protocol | Static analysis only | Advisory | Libraries that must accept many shapes |
ABC with abstractmethod | At instantiation | Hard | Hierarchies you own and extend |
__init_subclass__ | At subclass definition | Medium | Registration and validation of subclasses |
| Metaclass | At class creation | Hard, global | Frameworks governing every class |
The practical escalation path: start with duck typing, add a protocol when type checking begins to catch mistakes, introduce an ABC when you find yourself re-implementing the same guard clause, and only then consider a metaclass. Skipping straight to the strictest tool buys very little and imposes a tax on every reader who now has to understand the machinery before they can follow the logic.
Common Mistakes
Declaring __slots__ in a base class and expecting subclasses to be unaffected
Fix: Subclasses without their own slots get a __dict__ anyway, so measure the real allocation before claiming a saving
Storing descriptor state on the attribute the descriptor intercepts
Fix: Write to a separate private name, or the descriptor recurses until Python raises a maximum recursion error
Using a metaclass where a decorator or __init_subclass__ would do
Fix: Reach for __init_subclass__ first; it affects only your hierarchy and keeps type as the metaclass
Making every method abstract in an ABC
Fix: Keep the abstract surface small and inherit shared concrete behaviour from the base
Accessing an attribute on the class in __get__ without the instance-is-None check
Fix: Return the descriptor itself when instance is None so class-level access keeps working
Best Practices
- Validate at construction with ABC so missing methods fail before any state is touched
- Apply __slots__ only to high-count data records, and verify with tracemalloc
- Write descriptors with __set_name__ so one class can manage many fields
- Prefer __init_subclass__ over metaclasses unless every class statement must be intercepted
- Document the contract in docstrings, not only in method names
Interview Questions
Q1: What is the difference between property and a descriptor?
property is a built-in read-only descriptor implemented with three methods. A custom descriptor is any object defining __get__, __set__, or __delete__; it lets you validate, convert, or lazily compute, and __set_name__ lets one descriptor class serve several attributes.
Q2: When does a metaclass beat __init_subclass__?
When you must influence the class object itself â renaming, altering the namespace, or enforcing rules on every class statement including third-party ones. __init_subclass__ only observes subclasses of your base and cannot change how the class is built.
Q3: What does __slots__ actually save?
It removes the per-instance __dict__ and replaces it with fixed descriptors, cutting memory and speeding attribute access. The saving disappears for subclasses that do not declare their own slots, and you lose the ability to add undeclared attributes.
Key Takeaways
- ABCs fail at instantiation, which is earlier and clearer than a NotImplementedError later
- slots trade attribute flexibility for memory and speed on high-count records
- Descriptors intercept attribute access; property is simply the built-in read-only one
- Metaclasses act at class creation â try __init_subclass__ or a decorator first
- Escalate interface tools from duck typing to protocol to ABC only as strictness earns its cost