@Oddthinking's answer is not wrong, but I think it misses the real, practical reason Python has ABCs in a world of duck-typing.

Abstract methods are neat, but in my opinion they don't really fill any use-cases not already covered by duck typing. Abstract base classes' real power lies in the way they allow you to customise the behaviour of isinstance and issubclass. (__subclasshook__ is basically a friendlier API on top of Python's __instancecheck__ and __subclasscheck__ hooks.) Adapting built-in constructs to work on custom types is very much part of Python's philosophy.

Python's source code is exemplary. Here is how collections.Container is defined in the standard library (at time of writing):

class Container(metaclass=ABCMeta):
    __slots__ = ()

    @abstractmethod
    def __contains__(self, x):
        return False

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Container:
            if any("__contains__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

This definition of __subclasshook__ says that any class with a __contains__ attribute is considered to be a subclass of Container, even if it doesn't subclass it directly. So I can write this:

class ContainAllTheThings(object):
    def __contains__(self, item):
        return True

>>> issubclass(ContainAllTheThings, collections.Container)
True
>>> isinstance(ContainAllTheThings(), collections.Container)
True

In other words, if you implement the right interface, you're a subclass! ABCs provide a formal way to define interfaces in Python, while staying true to the spirit of duck-typing. Besides, this works in a way that honours the Open-Closed Principle.

Python's object model looks superficially similar to that of a more "traditional" OO system (by which I mean Java*) - we got yer classes, yer objects, yer methods - but when you scratch the surface you'll find something far richer and more flexible. Likewise, Python's notion of abstract base classes may be recognisable to a Java developer, but in practice they are intended for a very different purpose.

I sometimes find myself writing polymorphic functions that can act on a single item or a collection of items, and I find isinstance(x, collections.Iterable) to be much more readable than hasattr(x, '__iter__') or an equivalent try...except block. (If you didn't know Python, which of those three would make the intention of the code clearest?)

That said, I find that I rarely need to write my own ABC and I typically discover the need for one through refactoring. If I see a polymorphic function making a lot of attribute checks, or lots of functions making the same attribute checks, that smell suggests the existence of an ABC waiting to be extracted.

*without getting into the debate over whether Java is a "traditional" OO system...


Addendum: Even though an abstract base class can override the behaviour of isinstance and issubclass, it still doesn't enter the MRO of the virtual subclass. This is a potential pitfall for clients: not every object for which isinstance(x, MyABC) == True has the methods defined on MyABC.

class MyABC(metaclass=abc.ABCMeta):
    def abc_method(self):
        pass
    @classmethod
    def __subclasshook__(cls, C):
        return True

class C(object):
    pass

# typical client code
c = C()
if isinstance(c, MyABC):  # will be true
    c.abc_method()  # raises AttributeError

Unfortunately this one of those "just don't do that" traps (of which Python has relatively few!): avoid defining ABCs with both a __subclasshook__ and non-abstract methods. Moreover, you should make your definition of __subclasshook__ consistent with the set of abstract methods your ABC defines.

Answer from Benjamin Hodgson on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ abc.html
abc โ€” Abstract Base Classes
In addition, the collections.abc submodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping. This module provides the metaclass ABCMeta for defining ABCs and a helper class ABC to alternatively define ABCs through inheritance:
๐ŸŒ
Medium
leapcell.medium.com โ€บ elegant-abstractions-mastering-abstract-base-classes-in-advanced-python-bf3739dd815e
Elegant Abstractions: Mastering ABCs in Advanced Python | by Leapcell | Medium
May 2, 2025 - For example, when you need to combine the functions of multiple metaclasses: class MyMeta(type): def __new__(cls, name, bases, namespace): # Custom metaclass behavior return super().__new__(cls, name, bases, namespace) class CombinedMeta(ABCMeta, ...
Top answer
1 of 6
351

@Oddthinking's answer is not wrong, but I think it misses the real, practical reason Python has ABCs in a world of duck-typing.

Abstract methods are neat, but in my opinion they don't really fill any use-cases not already covered by duck typing. Abstract base classes' real power lies in the way they allow you to customise the behaviour of isinstance and issubclass. (__subclasshook__ is basically a friendlier API on top of Python's __instancecheck__ and __subclasscheck__ hooks.) Adapting built-in constructs to work on custom types is very much part of Python's philosophy.

Python's source code is exemplary. Here is how collections.Container is defined in the standard library (at time of writing):

class Container(metaclass=ABCMeta):
    __slots__ = ()

    @abstractmethod
    def __contains__(self, x):
        return False

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Container:
            if any("__contains__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

This definition of __subclasshook__ says that any class with a __contains__ attribute is considered to be a subclass of Container, even if it doesn't subclass it directly. So I can write this:

class ContainAllTheThings(object):
    def __contains__(self, item):
        return True

>>> issubclass(ContainAllTheThings, collections.Container)
True
>>> isinstance(ContainAllTheThings(), collections.Container)
True

In other words, if you implement the right interface, you're a subclass! ABCs provide a formal way to define interfaces in Python, while staying true to the spirit of duck-typing. Besides, this works in a way that honours the Open-Closed Principle.

Python's object model looks superficially similar to that of a more "traditional" OO system (by which I mean Java*) - we got yer classes, yer objects, yer methods - but when you scratch the surface you'll find something far richer and more flexible. Likewise, Python's notion of abstract base classes may be recognisable to a Java developer, but in practice they are intended for a very different purpose.

I sometimes find myself writing polymorphic functions that can act on a single item or a collection of items, and I find isinstance(x, collections.Iterable) to be much more readable than hasattr(x, '__iter__') or an equivalent try...except block. (If you didn't know Python, which of those three would make the intention of the code clearest?)

That said, I find that I rarely need to write my own ABC and I typically discover the need for one through refactoring. If I see a polymorphic function making a lot of attribute checks, or lots of functions making the same attribute checks, that smell suggests the existence of an ABC waiting to be extracted.

*without getting into the debate over whether Java is a "traditional" OO system...


Addendum: Even though an abstract base class can override the behaviour of isinstance and issubclass, it still doesn't enter the MRO of the virtual subclass. This is a potential pitfall for clients: not every object for which isinstance(x, MyABC) == True has the methods defined on MyABC.

class MyABC(metaclass=abc.ABCMeta):
    def abc_method(self):
        pass
    @classmethod
    def __subclasshook__(cls, C):
        return True

class C(object):
    pass

# typical client code
c = C()
if isinstance(c, MyABC):  # will be true
    c.abc_method()  # raises AttributeError

Unfortunately this one of those "just don't do that" traps (of which Python has relatively few!): avoid defining ABCs with both a __subclasshook__ and non-abstract methods. Moreover, you should make your definition of __subclasshook__ consistent with the set of abstract methods your ABC defines.

2 of 6
214

Short version

ABCs offer a higher level of semantic contract between clients and the implemented classes.

Long version

There is a contract between a class and its callers. The class promises to do certain things and have certain properties.

There are different levels to the contract.

At a very low level, the contract might include the name of a method or its number of parameters.

In a staticly-typed language, that contract would actually be enforced by the compiler. In Python, you can use EAFP or type introspection to confirm that the unknown object meets this expected contract.

But there are also higher-level, semantic promises in the contract.

For example, if there is a __str__() method, it is expected to return a string representation of the object. It could delete all contents of the object, commit the transaction and spit a blank page out of the printer... but there is a common understanding of what it should do, described in the Python manual.

That's a special case, where the semantic contract is described in the manual. What should the print() method do? Should it write the object to a printer or a line to the screen, or something else? It depends - you need to read the comments to understand the full contract here. A piece of client code that simply checks that the print() method exists has confirmed part of the contract - that a method call can be made, but not that there is agreement on the higher level semantics of the call.

Defining an Abstract Base Class (ABC) is a way of producing a contract between the class implementers and the callers. It isn't just a list of method names, but a shared understanding of what those methods should do. If you inherit from this ABC, you are promising to follow all the rules described in the comments, including the semantics of the print() method.

Python's duck-typing has many advantages in flexibility over static-typing, but it doesn't solve all the problems. ABCs offer an intermediate solution between the free-form of Python and the bondage-and-discipline of a staticly-typed language.

๐ŸŒ
Python Course
python-course.eu โ€บ oop โ€บ the-abc-of-abstract-base-classes.php
20. The 'ABC' of Abstract Base Classes | OOP | python-course.eu
This impression is wrong: An abstract method can have an implementation in the abstract class! Even if they are implemented, designers of subclasses will be forced to override the implementation. Like in other cases of "normal" inheritance, the abstract method can be invoked with super() call mechanism. This enables providing some basic functionality in the abstract method, which can be enriched by the subclass implementation. from abc import ABC, abstractmethod class AbstractClassExample(ABC): @abstractmethod def do_something(self): print("Some implementation!") class AnotherSubclass(AbstractClassExample): def do_something(self): super().do_something() print("The enrichment from AnotherSubclass") x = AnotherSubclass() x.do_something()
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ collections.abc.html
collections.abc โ€” Abstract Base Classes for Containers
Checking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an __iter__() method, but it does not detect classes that iterate with the __getitem__() method. The only reliable way to determine whether an object is iterable is to call iter(obj). ... ABC for sized iterable container classes.
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ glossary โ€บ abstract-base-class
abstract base class (ABC) | Python Glossary โ€“ Real Python
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def speak(self): pass def jump(self): return f"{self.__class__.__name__} is jumping" Animal is an abstract base class with an abstract method .speak() and a regular method .jump(). Subclasses must implement all methods marked with @abstractmethod: ... >>> from animals import Animal >>> class Dog(Animal): ... pass >>> Dog() Traceback (most recent call last): ... TypeError: Can't instantiate abstract class Dog โฎ‘ without an implementation for abstract method 'speak'
๐ŸŒ
Machine Learning Plus
machinelearningplus.com โ€บ python โ€บ python-abcs-the-complete-guide-to-abstract-base-classes
Python ABCs- The Complete Guide to Abstract Base Classes โ€“ Machine Learning Plus
You can use this directly if you need more control, but ABC is usually sufficient. Letโ€™s create a PaymentMethod abstract base class using ABCMeta directly instead of inheriting from ABC, with two abstract methods for payment processing.
๐ŸŒ
Python
peps.python.org โ€บ pep-3119
PEP 3119 โ€“ Introducing Abstract Base Classes | peps.python.org
During the development of this PEP and of its companion, PEP 3141, we repeatedly faced the choice between standardizing more, fine-grained ABCs or fewer, coarse-grained ones. For example, at one stage, PEP 3141 introduced the following stack of base classes used for complex numbers: MonoidUnderPlus, AdditiveGroup, Ring, Field, Complex (each derived from the previous).
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ abstract-base-class-abc-in-python
Abstract Base Class (abc) in Python - GeeksforGeeks
July 15, 2025 - It often serves as an alternative to subclassing a built-in Python class. For example, subclassing the MutableSequence can substitute the subclassing of list or str. The main purpose of using Abstract class is that it allows you to consider a common type of collection rather than coding for each type of collection. Here we will discuss Single-Method ABCs and Alternative-Collection ABCs.
๐ŸŒ
The Python Coding Stack
thepythoncodingstack.com โ€บ p โ€บ and-now-you-know-your-abc-python-abstract-base-classes
And Now You Know Your ABC - by Stephen Gruppetta
November 1, 2025 - Python is expecting a concrete implementation of this method. Any class that inherits from the Event ABC must have a concrete implementation of this method. Letโ€™s fix this: ... In TrackEvent, you include the same code you had in the original Event.finalise_results() since this algorithm works well for track events where the smallest numbers (the fastest times) represent the best performances.
๐ŸŒ
The Teclado Blog
blog.teclado.com โ€บ python-abc-abstract-base-classes
How to Write Cleaner Python Code Using Abstract Classes
October 26, 2022 - What are Abstract Classes? Why are they useful? When should you use them? Let me give you a few examples and explanations! By the end of this post, you'll have a firm understanding of ABCs in Python, and how to add them to your programs. Let's begin! I believe the best way to learn is with ...
๐ŸŒ
DEV Community
dev.to โ€บ leapcell โ€บ elegant-abstractions-mastering-abcs-in-advanced-python-4k6d
Elegant Abstractions: Mastering Abstract Base Classes in Advanced Python - DEV Community
May 2, 2025 - For example, when you need to combine the functions of multiple metaclasses: class MyMeta(type): def __new__(cls, name, bases, namespace): # Custom metaclass behavior return super().__new__(cls, name, bases, namespace) class CombinedMeta(ABCMeta, ...
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ stdlib โ€บ abc
abc | Python Standard Library โ€“ Real Python
The Python abc module provides infrastructure for defining abstract base classes (ABCs).
Top answer
1 of 3
10

SubQuery is an abstract base class (per the abc module) with one or more abstract methods that you did not override. By adding ABC to the list of base classes, you defined ValueSum itself to be an abstract base class. That means you aren't forced to override the methods, but it also means you cannot instantiate ValueSum itself.

PyCharm is warning you ahead of time that you need to implement the abstract methods inherited from SubQuery; if you don't, you would get an error from Python when you actually tried to instantiate ValueSum.


As to what inheriting from ABC does, the answer is... not much. It's a convenience for setting the metaclass. The following are equivalent:

class Foo(metaclass=abc.ABCMeta):
    ...

and

class Foo(abc.ABC):
    ...

The metaclass modifies __new__ so that every attempt to create an instance of your class checks that the class has implemented all methods decorated with @abstractmethod in a parent class.

2 of 3
4

The 'Abstract Base classes" or abc.ABC is a helper class

https://docs.python.org/3/library/abc.html

Here's a snippet of why they exist:

The collections module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition, the collections.abc submodule has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, if it is hashable or if it is a mapping.

A good example here: https://pymotw.com/2/abc/ | https://pymotw.com/3/abc/

From pymotw:

Forgetting to set the metaclass properly means the concrete implementations do not have their APIs enforced. To make it easier to set up the abstract class properly, a base class is provided that sets the metaclass automatically.

abc_abc_base.py
import abc


class PluginBase(abc.ABC):

    @abc.abstractmethod
    def load(self, input):
        """Retrieve data from the input source
        and return an object.
        """

    @abc.abstractmethod
    def save(self, output, data):
        """Save the data object to the output."""


class SubclassImplementation(PluginBase):

    def load(self, input):
        return input.read()

    def save(self, output, data):
        return output.write(data)


if __name__ == '__main__':
    print('Subclass:', issubclass(SubclassImplementation,
                                  PluginBase))
    print('Instance:', isinstance(SubclassImplementation(),
                                  PluginBase))
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-abstract-classes
Python Abstract Classes: A Comprehensive Guide with Examples | DataCamp
January 22, 2025 - Learn about Python abstract classes, their purpose, and how to use the `abc` module to enforce consistent interfaces. Includes practical examples and best practices for effective implementation.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_abstract_base_classes.htm
Python - Abstract Base Classes
An Abstract Base Class (ABC) in Python is a class that cannot be instantiated directly and is intended to be subclassed. ABCs serve as blueprints for other classes by providing a common interface that all subclasses must implement.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_module_abc.asp
Python abc Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ understanding abc.abc
r/learnpython on Reddit: Understanding abc.ABC
June 20, 2023 -

I am being asked to maintain code that subclasses from abc.ABC. I have read the python documentation, the associated PEP, and even visited pymotw. I do not understand what abstract classes give you.

If I have class A and then I derive subclass B from it wouldn't issubclass(B,A) still be true?

Top answer
1 of 4
4
If I have class A and then I derive subclass B from it wouldn't issubclass(B,A) still be true? Usually, yes, unless you do something weird with metaclasses maybe. I do not understand what abstract classes give you. You can think of them as some kind of "contracts"; any class inheriting from them implicitly makes a promise to support the interface defined by the abstract base class. It's not nearly as binding or robust as something like Rust's trait system, but it can still come in handy sometimes. For example, os.PathLike is an abstract base class that defines a common interface all path-like objects, such as pathlib.Path, must fulfill to be compatible with most standard library functions expecting filepaths as arguments. The subclasses can add more functionality on top of the required methods, but they are forced to at least have the ones set by the abstract base class. In other words, you can always count on those being available no matter what kind of subclass you're getting.
2 of 4
4
Abstract base classes are just classes that aren't meant to be instantiated. It is like a wireframe for shared methods / attributes, without the ABC itself being a legitimate object type. It works the same as regular subclassing in most ways. ABCs usually have the shared methods defined so that if you make a subclass of it and it doesn't implement something the interface was expected to it will throw an error. class PersonNormal: def __init__(self, name: str): self.name = name def say_hi(self): print(f"Hi, I'm {self.name}") class PersonABC(ABC): def __init__(self, name): ... @abstractmethod def say_hi(self): ... class Student(Person): def __init__(self, name: str): super().__init__(name) class Teacher(Person) def __init__(self, name: str): super().__init__(name) def say_hi(self): print(f"Good morning, I'm Mr. {self.name}") # inheriting from PersonNormal A = Person('John') B = Student('Peter') C = Teacher('Tom') A.say_hi() # calls Person.say_hi normally B.say_hi() # calls Person.say_hi since it wasn't overwritten C.say_hi() # calls Teacher.say_hi # inheriting from PersonABC A = Person('John') # TypeError can't instantiate abstract class Person... B = Student('Peter') # TypeError since you didn't overwrite the method C = Teacher('Tom') # works as expected
๐ŸŒ
Justin A. Ellis
jellis18.github.io โ€บ post โ€บ 2022-01-11-abc-vs-protocol
Abstract Base Classes and Protocols: What Are They? When To Use Them?? Lets Find Out! - Justin A. Ellis
January 11, 2022 - Use ABCs if you will need several implementations of a class with several methods. Use Protocols for strict type annotations (i.e.only annotate the methods/attributes you need) ... Well, thats it for this time. Now go forth into our bold almost statically typed python future with confidence!