Tools
Log in
English

Learn to codePython

Python abstraction

Based on Python 3.12abstract method error text · Python 3.12+

Python ABC and @abstractmethod in a report template, and when to use Protocol.

In one line

The parent states what must exist (method names and shapes) and leaves how to do it to the children. In Python you use ABC and @abstractmethod from the abc module.

Why you need it

Copy the title line and line-count footer into every report type, and changing the footer means editing them all. Use a plain parent class instead, and a child that forgets the body method goes unnoticed until it runs.

Let the parent own the outline in render() and make body() abstract. The outline is fixed in one place, and a child without body fails as soon as it is created.

Everyday picture

Think of a job application form. The form fixes the order and layout of the boxes; applicants fill in only the experience box. Leave it blank and the desk hands it straight back. The form is the abstract class, the experience box the abstract method.

Example code

main.py · 45 lines
from abc import ABC, abstractmethod  class Report(ABC):    def __init__(self, title):        self.title = title     def render(self):        lines = [f"== {self.title} =="]        lines += self.body()        lines.append(f"({len(lines) - 1} lines)")        return "\n".join(lines)     @abstractmethod    def body(self):        ...  class SalesReport(Report):    def __init__(self, sales):        super().__init__("Sales")        self.sales = sales     def body(self):        total = sum(self.sales.values())        return [f"{day}: {n}" for day, n in self.sales.items()] + [f"total: {total}"]  class StockReport(Report):    def __init__(self, stock, low=5):        super().__init__("Stock")        self.stock = stock        self.low = low     def body(self):        return [f"{item} is low ({n})" for item, n in self.stock.items() if n < self.low]  try:    Report("Empty")except TypeError as e:    print("TypeError:", e)sales = SalesReport({"mon": 120, "tue": 95})print(sales.render())print(StockReport({"pen": 3, "ink": 12, "tape": 1}).render())

Three ways to require a method

ABC + @abstractmethodraise NotImplementedErrortyping.Protocol
Must subclassOOX
When a missing method shows upWhen the object is createdWhen the method is calledWhen a type checker (mypy) runs
Can hold shared codeOOX
Good fitThe parent owns the outline and orderSmall scripts, quick startAccepting classes you did not write

typing.Protocol exists since Python 3.8. A class that has the right method names and signatures counts as following the contract without inheriting.

When to use it

  • The steps are the same and only one or two differ per kind (reports, file readers, checkout flows)
  • Several people write child classes that plug into one structure
  • Forgetting a method would cause real damage

The wording "without an implementation for abstract method" is from Python 3.12. Up to 3.11 the message reads "with abstract method body".

Common mistakes

Inheriting ABC without @abstractmethod

Subclassing ABC on its own enforces nothing; the empty body quietly returns None. Mark required methods with @abstractmethod so creation fails until they are filled in.

Wrong

from abc import ABC  class Report(ABC):    def body(self):        pass  r = Report()print(r.body())

When you run itNone

Fixed

from abc import ABC, abstractmethod  class Report(ABC):    @abstractmethod    def body(self):        ...  try:    Report()except TypeError:    print("make a subclass first")

When you run itmake a subclass first

Misspelling the abstract method

bodyy is a different method, so body is still empty. The error appears the moment you create the object, not halfway through a run.

Wrong

class DailyReport(Report):    def bodyy(self):        return ["ok"]  DailyReport("Daily")

When you run itTypeError: Can't instantiate abstract class DailyReport without an implementation for abstract method 'body'

Fixed

class DailyReport(Report):    def body(self):        return ["ok"]  print(DailyReport("Daily").render())

When you run it== Daily == ok (1 lines)

Returning a different shape than promised

The parent expects body() to return a list of lines and extends with lines +=. A plain string gets split into single characters. The return shape is part of the contract, not just the name.

Wrong

class NoteReport(Report):    def body(self):        return "ok"  print(NoteReport("Notes").render())

When you run it== Notes == o k (2 lines)

Fixed

class NoteReport(Report):    def body(self):        return ["ok"]  print(NoteReport("Notes").render())

When you run it== Notes == ok (1 lines)

Check yourself

Question 1

What happens on Report("X"), creating the abstract class directly?

Show the answer

Answer: 2. A `TypeError` when the object is created body is an empty @abstractmethod, so creation itself raises TypeError.

Question 2

How many lines does printing StockReport({"pen": 3, "ink": 2}, low=3).render() give?

print(StockReport({"pen": 3, "ink": 2}, low=3).render())

Show the answer

Answer: 2. 3 Only items below 3 are kept, so just ink. With the header and footer, that is 3 lines.

Questions people ask

Why can I not create an abstract class directly?

If a method marked @abstractmethod is still empty, Python refuses to create the object, so a missing method is caught before anything runs.

How is this different from raising NotImplementedError?

NotImplementedError only fails when the method is called. An ABC tells you as soon as the object is created.

When do I use typing.Protocol?

When classes that do not inherit from you should still be accepted if their methods match. A type checker such as mypy does the checking.