๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ abc.html
abc โ€” Abstract Base Classes
For a demonstration of these concepts, look at this example ABC definition: class Foo: def __getitem__(self, index): ... def __len__(self): ...
๐ŸŒ
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()
๐ŸŒ
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 class Square(Shape): def __init__(self, s): self.s = s def area(self): return self.s * self.s sq = Square(3) print(isinstance(sq, Shape)) print(sq.area()) Try it Yourself ยป
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ glossary โ€บ abstract-base-class
abstract base class (ABC) | Python Glossary โ€“ Real Python
To define an abstract base class, you inherit from abc.ABC and use the @abstractmethod decorator to mark methods that must be implemented by subclasses. Attempting to instantiate an abstract base class or a subclass that hasnโ€™t implemented all abstract methods will raise a TypeError exception. Hereโ€™s an example of how to define and use an abstract base class in Python...
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ collections.abc.html
collections.abc โ€” Abstract Base Classes for Containers
For example, knowing that a class supplies __getitem__, __len__, and __iter__ is insufficient for distinguishing a Sequence from a Mapping. Added in version 3.9: These abstract classes now support []. See Generic Alias Type and PEP 585. ... These ABCs override __subclasshook__() to support testing an interface by verifying the required methods are present and have not been set to None.
๐ŸŒ
Python
docs.python.org โ€บ 3.8 โ€บ library โ€บ abc.html
abc โ€” Abstract Base Classes โ€” Python 3.8.20 documentation
For a demonstration of these concepts, look at this example ABC definition: class Foo: def __getitem__(self, index): ... def __len__(self): ...
๐ŸŒ
Python
docs.python.org โ€บ 3.10 โ€บ library โ€บ abc.html
abc โ€” Abstract Base Classes โ€” Python 3.10.18 documentation
For a demonstration of these concepts, look at this example ABC definition: class Foo: def __getitem__(self, index): ... def __len__(self): ...
๐ŸŒ
Python
peps.python.org โ€บ pep-3119
PEP 3119 โ€“ Introducing Abstract Base Classes | peps.python.org
Another example would be someone who wants to define a generic function (PEP 3124) for any sequence that has an append() method. The Sequence ABC (see below) doesnโ€™t promise the append() method, while MutableSequence requires not only append() but also various other mutating methods. To solve these and similar dilemmas, the next section will propose a metaclass for use with ABCs that will allow us to add an ABC as a โ€œvirtual base classโ€ (not the same concept as in C++) to any class, including to another ABC.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ abc
abc โ€“ Abstract Base Classes - Python Module of the Week
Since ABCWithConcreteImplementation is an abstract base class, it isnโ€™t possible to instantiate it to use it directly. Subclasses must provide an override for retrieve_values(), and in this case the concrete class massages the data before returning it at all. $ python abc_concrete_method.py base class reading data subclass sorting data ['line one', 'line three', 'line two']
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ abstract-base-class-abc-in-python
Abstract Base Class (abc) in Python - GeeksforGeeks
July 15, 2025 - The main purpose of using Abstract ... ABCs and Alternative-Collection ABCs. ... Python has five abstract base classes. They are as follows: ... These abstract base classes contain one abstract method each. Let's consider an example of the __len__ method....
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-abstract-classes
Python Abstract Classes: A Comprehensive Guide with Examples | DataCamp
January 22, 2025 - You can make sure that any subclass, such as Dog or Cat, implements its implementation of the speak method, for instance, if you have an abstract class Animal with an abstract method speak. Your code becomes reliable and predictable as a result of this uniformity. Master Python for data science and gain in-demand skills. ... The abc module in Python offers strong built-in support for abstract classes.
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))
๐ŸŒ
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 - class ABC(metaclass=ABCMeta): """Helper class that provides a standard way to create an ABC using inheritance. """ pass ยท The code is more concise. It is more in line with the principle of simplicity and intuitiveness in Python. It is the recommended way in Python 3. When your class already has other metaclasses. When you need to customize the behavior of the metaclass. For example, when you need to combine the functions of multiple metaclasses:
๐ŸŒ
Earthly
earthly.dev โ€บ blog โ€บ abstract-base-classes-python
Abstract Base Classes in Python - Earthly Blog
July 19, 2023 - Learn how to create Abstract Base Classes (ABCs) in Python to enforce the implementation of certain methods or attributes in subclasses. ABCs promo...
๐ŸŒ
The Teclado Blog
blog.teclado.com โ€บ python-abc-abstract-base-classes
How to Write Cleaner Python Code Using Abstract Classes
October 26, 2022 - Take a look at the code of Animal, Lion and Snake: from abc import ABC, abstractmethod class Animal(ABC): @property def food_eaten(self): return self._food @food_eaten.setter def food_eaten(self, food): if food in self.diet: self._food = food ...
๐ŸŒ
Pybites
pybit.es โ€บ articles โ€บ elevate-your-python-harnessing-the-power-of-abstract-base-classes-abcs
Elevate Your Python: Harnessing The Power Of Abstract Base Classes (ABCs) - Pybites
February 21, 2024 - ยท Iterable, Iterator, Sequence (and others): These ABCs in the collections.abc module are used to define the expected methods for iterable objects (like lists and tuples), iterators, and sequence types.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ abstract-classes-in-python
Abstract Classes in Python - GeeksforGeeks
Example: This example shows the error raised when trying to instantiate an abstract class. ... from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass # animal = Animal() # TypeError: Can't instantiate abstract class Animal with abstract methods make_sound
Published ย  September 3, 2025
๐ŸŒ
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.
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.