liveBook · Manning

Abstractmethod

As explained in Practices of the Python Pro

abstractmethod is a decorator from Python's abc module that marks a method as abstract and requires concrete subclasses to implement it.

abstractmethod is a decorator from Python’s abc module that marks a method as required by every concrete subclass. It turns an abstract base class into a template for shared behavior: subclasses must provide the marked method before they can be instantiated. section 8.3.4

Listing 8.4. Using abstract base classes to enforce an interface
from abc import ABC, abstractmethod


class Predator(ABC):                   #1
    @abstractmethod                    #2
    def eat(self, prey):               #3
        pass                           #4


class Bear(Predator):                  #5
    def eat(self, prey):               #6
        print(f'Mauling {prey}!')


class Owl(Predator):
    def eat(self, prey):
        print(f'Swooping in on {prey}!')


class Chameleon(Predator):
    def eat(self, prey):
        print(f'Shooting tongue at {prey}!')


if __name__ == '__main__':
    bear = Bear()
    bear.eat('deer')
    owl = Owl()
    owl.eat('mouse')
    chameleon = Chameleon()
    chameleon.eat('fly')

A Predator base class marks eat as abstract, while Bear, Owl, and Chameleon each provide their own implementation. section 8.3.4

Use abstractmethod to make an interface explicit and catch incomplete subclasses early:

  • Import ABC and abstractmethod, then inherit the base class from ABC. section 8.3.4
  • Place @abstractmethod above each required method and define a consistent method signature. section 8.3.4 section 8.4.1
  • Expect TypeError when code tries to instantiate a subclass that has not implemented every abstract method. section 8.3.4

Commands with a shared execute method

A Command abstract base class can require execute(data). Existing command classes inherit from Command and normalize their methods to accept the same argument, preserving substitutability while allowing each command to act on data. section 8.4.1

How Practices of the Python Pro covers it

How deep it goes
Explains setup, enforcement, errors, and signatures, but treats decorator internals as a label and defers runtime signature checking.
Examples
Uses predator classes implementing eat and command classes sharing an execute method.
What it assumes
Assumes basic inheritance and method definitions, while treating decorators as labels rather than explaining their mechanics.
What you can do after
Build it from scratch by defining abstract base classes, enforcing required methods, and normalizing subclass signatures.
How it connects
Connects abstract base classes with inheritance, interfaces, decorators, method signatures, and the command pattern.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.