Explain Codes LogoExplain Codes Logo

Abstract methods in Python

python
abstract-methods
abc
metaclasses
Nikita BarsukovbyNikita Barsukov·Jan 28, 2025
TLDR

Abstract methods enforce a consistent interface by requiring subclasses to implement specific methods. This is achieved using the abc module and applying the @abstractmethod decorator. If a subclass does not override these methods, it cannot be instantiated. Observe:

from abc import ABC, abstractmethod class MyBase(ABC): """I'm a base class, don't touch me. Seriously, don't."}, @abstractmethod def my_method(self): """I'm abstract. Implement me or blame yourself.""" pass class MySubclass(MyBase): """Guess what? I'm a subclass and I follow the rules.""" def my_method(self): """I'm the dynamic method, I do as I please. Yay!""" return "Implemented!"

A Type Error pops up when trying to instantiate MyBase; it insists that my_method be defined.

Implementing abstract methods

Understanding and implementing abstract methods is as easy as ABC...literally. Use abc.ABC or metaclass=ABCMeta in your base class.

Common implementation issues

Avoid these frequent pitfalls when using abc:

  • Forgetting to import abstractmethod.
  • Not calling ABC or metaclass=ABCMeta in your base class.
  • Overriding an abstract method without actually implementing it.

Advanced ABC usage

Using ABCMeta alongside other metaclasses can be a fun challenge in complex class hierarchies.

class MetaClassOne(type): pass class MetaClassTwo(ABCMeta, MetaClassOne): pass class ComplexBase(metaclass=MetaClassTwo): @abstractmethod def a_complex_method(self): """I'm complex and abstract. Deal with it.""" pass

Alternatives to abstract base classes

In a legacy system or if you're dealing with zope.interface, you might need to explore alternatives. Raise NotImplementedError to signal unimplemented methods. But be aware: this lacks ABC's compile-time checks.

class LegacyBase: def my_legacy_method(self): """Not yet implemented. Coming Soon™.""" raise NotImplementedError("You must implement my_legacy_method.")

Implementing abstract methods: Python vs Java

In Python, abstract methods can have an implementation. super().method_name can be called from subclasses. Experience the freedom!

class MyFlexibleBase(ABC): @abstractmethod def flexible_method(self): """I'm flexible, I bend but don't break!""" print("This is an abstract method with some functionality.") class MyFlexibleSubclass(MyFlexibleBase): def flexible_method(self): """Inhaling the wisdom of ancestors one `super()` at a time.""" super().flexible_method() print("And this is the subclass implementation.")

Abstract base classes, duck typing, and dynamic checks

Abstract base classes combine the rigorousness of static typing with Python's duck typing. A class that doesn't conform to an ABC is as conspicuous as a cat at a duck party.

Ensuring dynamic checks

Python relies on AttributeError and TypeError to ensure that required attributes and methods exist at runtime. Like an alarm clock, it'll let you know loud and clear if something's amiss.