As mentioned by other here:

Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don't have to have them in Python.

That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.

Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC's for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework. Here you don't subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!

Answer from Lennart Regebro on Stack Overflow
🌐
Real Python
realpython.com › python-interface
Implementing an Interface in Python – Real Python
February 21, 2024 - This is done by classes, which then implement the interface and give concrete meaning to the interface’s abstract methods. Python’s approach to interface design is somewhat different when compared to languages like Java, Go, and C++. These languages all have an interface keyword, while Python does not.
Top answer
1 of 8
272

As mentioned by other here:

Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don't have to have them in Python.

That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.

Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC's for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework. Here you don't subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!

2 of 8
239

Implementing interfaces with abstract base classes is much simpler in modern Python 3 and they serve a purpose as an interface contract for plug-in extensions.

Create the interface/abstract base class:

from abc import ABC, abstractmethod

class AccountingSystem(ABC):

    @abstractmethod
    def create_purchase_invoice(self, purchase):
        pass

    @abstractmethod
    def create_sale_invoice(self, sale):
        log.debug('Creating sale invoice', sale)

Create a normal subclass and override all abstract methods:

class GizmoAccountingSystem(AccountingSystem):

    def create_purchase_invoice(self, purchase):
        submit_to_gizmo_purchase_service(purchase)

    def create_sale_invoice(self, sale):
        super().create_sale_invoice(sale)
        submit_to_gizmo_sale_service(sale)

You can optionally have common implementation in the abstract methods as in create_sale_invoice(), calling it with super() explicitly in the subclass as above.

Instantiation of a subclass that does not implement all the abstract methods fails:

class IncompleteAccountingSystem(AccountingSystem):
    pass

>>> accounting = IncompleteAccountingSystem()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class IncompleteAccountingSystem with abstract methods
create_purchase_invoice, create_sale_invoice

You can also have abstract properties, static and class methods by combining corresponding annotations with @abstractmethod.

Abstract base classes are great for implementing plugin-based systems. All imported subclasses of a class are accessible via __subclasses__(), so if you load all classes from a plugin directory with importlib.import_module() and if they subclass the base class, you have direct access to them via __subclasses__() and you can be sure that the interface contract is enforced for all of them during instantiation.

Here's the plugin loading implementation for the AccountingSystem example above:

...
from importlib import import_module

class AccountingSystem(ABC):

    ...
    _instance = None

    @classmethod
    def instance(cls):
        if not cls._instance:
            module_name = settings.ACCOUNTING_SYSTEM_MODULE_NAME
            import_module(module_name)
            subclasses = cls.__subclasses__()
            if len(subclasses) > 1:
                raise InvalidAccountingSystemError('More than one '
                        f'accounting module: {subclasses}')
            if not subclasses or module_name not in str(subclasses[0]):
                raise InvalidAccountingSystemError('Accounting module '
                        f'{module_name} does not exist or does not '
                        'subclass AccountingSystem')
            cls._instance = subclasses[0]()
        return cls._instance

Then you can access the accounting system plugin object through the AccountingSystem class:

>>> accountingsystem = AccountingSystem.instance()

(Inspired by this PyMOTW-3 post.)

Discussions

Classes and Implementing Interfaces
Take a look here: https://realpython.com/python-interface/ More on reddit.com
🌐 r/learnpython
10
1
February 9, 2021
Native Interface Support in Python - Ideas - Discussions on Python.org
Dear Python Community, I would like to propose the addition of native interface support in Python to enhance code clarity, enforce contracts, and facilitate the implementation of design patterns. The introduction of interfaces as a language feature would not only improve the maintainability ... More on discuss.python.org
🌐 discuss.python.org
1
September 22, 2023
How do I implement interfaces in python?
In Python, interfaces are not explicitly supported as they are in Java or C#. However, you can achieve interface-like behavior using abstract base classes (ABCs) provided by the abc module. Abstract base classes allow you to define methods that must be implemented by derived (subclass) classes, ... More on designgurus.io
🌐 designgurus.io
1
10
November 23, 2024
How to implement interfaces in Python effectively? - TestMu AI Community
How do I implement interfaces in Python? In C#, I can define an interface and implement it as shown below: public interface IInterface { void show(); } public class MyClass : IInterface { #region IInterface Members public void show() { Console.WriteLine("Hello World!"); } #endregion } I tried ... More on community.testmu.ai
🌐 community.testmu.ai
0
November 11, 2024
🌐
Chelsea Troy
chelseatroy.com › 2020 › 11 › 14 › why-use-or-not-use-interfaces-in-python
Why use (or not use) interfaces in Python? – Chelsea Troy
November 15, 2020 - An abstract class implements some ... as Python is concerned, an interface is just a special case of abstract class that implements no methods and requires subclasses to implement all the methods....
🌐
Tutorialspoint
tutorialspoint.com › python › python_interfaces.htm
Python - Interfaces
We can create and implement interfaces in two ways − ... Formal interfaces in Python are implemented using abstract base class (ABC).
🌐
Medium
medium.com › @shashikantrbl123 › interfaces-and-abstract-classes-in-python-understanding-the-differences-3e5889a0746a
Interfaces and Abstract Classes in Python: Understanding the Differences | by Shashi Kant | Medium
April 10, 2023 - For example, suppose we have a Shape interface that specifies a single method, area(). We can define the Shape interface in Python using the abc module as follows: from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass · Now, any class that implements the Shape interface must provide an implementation of the area() method.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-interface-module
Python-interface module - GeeksforGeeks
March 26, 2020 - Interface acts as a blueprint for designing classes, so interfaces are implemented using implementer decorator on class. If a class implements an interface, then the instances of the class provide the interface.
Find elsewhere
🌐
Python.org
discuss.python.org › ideas
Native Interface Support in Python - Ideas - Discussions on Python.org
September 22, 2023 - Dear Python Community, I would like to propose the addition of native interface support in Python to enhance code clarity, enforce contracts, and facilitate the implementation of design patterns. The introduction of int…
🌐
Kansas State University
textbooks.cs.ksu.edu › cc410 › i-oop › 06-inheritance-polymorphism › 06-python-interfaces › index.html
Python Interfaces :: CC 410 Textbook
June 17, 2024 - When we use the Python issubclass method, it will call this method behind the scenes. See below for a discussion of what that method does. Then, each property and method in the interface is implemented as an abstract method using the @abc.abstractmethod decorator.
🌐
Medium
medium.com › towardsdev › interfaces-en-python-2a7365a9ba14
Interfaces in Python
April 11, 2025 - In Python, the concept of an ... Java or C#), but it can be achieved — and is recommended — using Abstract Base Classes (ABCs) or Protocols (PEP 544)....
🌐
DEV Community
dev.to › alvesjessica › interfaces-in-python-not-truly-an-interface-just-a-convention-43d3
Interfaces in Python: not truly an interface, just a convention. - DEV Community
September 14, 2022 - class GameInterface: def start(self): ... as an interface but it’s not truly an interface. Once in Python there are no implements or interface keywords and we’re creating something by convention, to use the interface we created, ...
🌐
Medium
medium.com › @tomisinabiodun › how-to-implement-an-interface-in-python-6d3658d248c
How to Implement an Interface in Python | by Tomisin Abiodun | Medium
April 6, 2022 - But, with an interface, the class itself will become invalid once there’s a mismatch with the interface’s contract — the class must stick with the interface, and have a different method, if it needs to change the signature. This way, all the seventeen references of the class are pretty much safe in the way they call the utility method. ... Now, at some point in time, we Python-istas have needed a way to enforce implementations of certain methods in our classes, and you are probably reading this article because you have discovered that there are no native implementations of interfaces in Python.
🌐
Scaler
scaler.com › home › topics › interface in python
Interface in Python - Scaler Topics
June 23, 2024 - Even if both objects have the same function swim, we can now tell which one implements the Boat interface and which one implements the Fish interface. We recently learned how to write our own abstract base classes. However, creating custom abstract base classes is frequently discouraged in favor of using subclasses; the built-in ones. The Python standard library has a plethora of helpful ABCs that we may simply reuse.
🌐
TestMu AI Community
community.testmu.ai › ask a question
How to implement interfaces in Python effectively? - TestMu AI Community
November 11, 2024 - How do I implement interfaces in Python? In C#, I can define an interface and implement it as shown below: public interface IInterface { void show(); } public class MyClass : IInterface { #region IInterface Members public void show() { Console.WriteLine("Hello World!"); } #endregion } I tried to create a Python equivalent for this using the following code: class IInterface(object): def init(self): pass def show(self): raise Exception("NotImplementedException") class MyClass(IInte...
🌐
Reddit
reddit.com › r/python › interfaces in python
r/Python on Reddit: Interfaces in Python
June 24, 2022 - This includes pythonic "foo_bar" -> "FooBar" naming of created objects ... You don't usually need these facilities. Therefore, if you want the runtime check, it may be easier to copy the five lines of code into an __init_subclass__ method. However, I suggest that you don't inherit from abc.ABC at all and simply · continue to decorate your methods using abc.abstractmethod, and ... Also, when implementing an interface, you may want to use the new typing.override decorator (available as typing_extensions.override).
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › interface in python
Interface in Python | How to Create Interface in Python with Examples
May 14, 2024 - An informal interface in python is termed as a protocol because it is informal and cannot be formally enforced. It is mostly defined by templates or demonstrates in the documentations. Consider some of the methods we usually used – __len__, __iter__, __contains__ and all, which are used to perform some operation or set of protocols. Let see an example of python code to implements the – __len__, __iter__, __contains__ methods to apply on user define class instance or object, as in the below-given code –
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
YouTube
youtube.com › watch
Python Interfaces and Abstract Base Class (ABC): A Must-Know for Advanced Programmers - YouTube
Take your Python programming skills to the next level with this must-know topic: interfaces and abstract classes. Learn how to implement these important conc...
Published   February 22, 2024
Top answer
1 of 3
5

Using Python's multiple inheritance (MI) for interfaces, abstract base classes, mixins, or similar techniques is perfectly fine. In most cases, the MRO produces intuitive results.

However, object initialization under multiple inheritance is really tricky. In Python you cannot combine multiple classes per MI unless all participating classes have been designed for MI. The issue is that the __init__() method cannot know from which class it will be called and what the signature of the super().__init__() method will be. Effectively, this means that MI constructors:

  • must call the super().__init__()
  • must only take arguments by name, not by position
  • must forward any **kwargs to the super().__init__()
  • must not warn on unexpected arguments

Where possible, the better alternative is to avoid __init__() methods for interface-like classes, and instead express requirements through abstract methods. For example, instead of a BananaContainer class, we might write this interface/ABC:

import abc  # abstract base class

class BananaContainer(abc.ABC):
  @property
  @abc.abstractmethod
  def bananas(self) -> list:
    raise NotImplementedError

If a class wants to be a BananaContainer, it would have to implement that property.

In general, it is perfectly alright if you have a class that inherits from multiple interfaces or mixins. Aside from name collisions, the above __init__() problems, and general API bloat of the class, no noteworthy issues arise.


The second part of your question proposes a capability-based approach instead of using inheritance. Using composition instead of inheritance is often a very very good idea. For example, you eliminate the initialization problems by design. It also tends to lead to more explicit APIs that are easier to navigate and avoid name clashes. There should be some method that either returns an object representing a capability, or None if the capability isn't supported.

But these capabilities can be implemented in different ways: either by using normal composition, or by storing the capabilities in your own data structures.

  • Unless you have special needs for the object model, stick to the language. Store methods in normal object fields, provide normal methods to access them. This leads to a more comfortable API, and is more likely to support auto-completer and type-checkers.

  • If you need to modify the available capabilities of an object at run-time, and need to introduce new kinds of capabilities at run-time, then using a dictionary may be appropriate. But at this point you are inventing your own object system. This may be a good idea e.g. in games that have complex capability systems where new capabilities shall be defined in configuration files.

    Most software does not have these requirements, and does not benefit from that kind of flexibility.

    Additionally, Python's built-in object system is flexible enough that you could create new types and new methods without having to create a new object system. Builtins like getattr(), setattr(), hasattr(), and the type() constructor come in handy here.

I would likely express an object that can have both AppleContainer and BananaContainer capabilities like this:

class BananaContainer:
  ...

class AppleContainer:
  ...

class HasCapabilities:
  def __init__(self, x, y, z):
    # somehow determine the appropriate capabilities and initialize them
    self._banana_container = BananaContainer(y) if x else None
    self._apple_container = AppleContainer(y)

  @property
  def as_banana_container(self) -> Optional[BananaContainer]:
    return self._banana_container

  @property
  def as_apple_container(self) -> Optional[AppleContainer]:
    return self._apple_container

o = HasCapabilities(...)
bc = o.as_banana_container
if bc is not None:
  bc.do_banana_things()

Or with Python 3.8 assignment expressions:

if (bc := o.as_banana_container) is not None:
  bc.do_banana_things()

If you want to have some custom mechanisms for reflection over capabilities, you can implement that on top of this solution, with some amount of boilerplate. If we want to be MI-safe, we might declare the following base class that all capability-having classes need to inherit:

class CapabilityReflection:
  # a base implementations so that actual implementations
  # can safely call super()._get_capabilities()
  def _list_capabilities(self):
    return ()

  def all_capabilities(self):
    """deduplicated set of capabilities that this object supports."""
    set(self._list_capabilities())

  def get_capability(self, captype):
    """find a capability by its type. Returns None if not supported."""
    return None

which in the above case would have been implemented as:

class HasCapabilities(CapabilityReflection):
  ...
  def _list_capabilities(self):
    caps = [  # go through properties in case they have been overridden
      self.as_banana_container,
      self.as_apple_container,
    ]
    yield from (cap for cap in caps if cap is not None)
    yield from super()._list_capabilities()

  def get_capability(self, captype):
    if captype == BananaContainer:
      return self.as_banana_container
    if captype == AppleContainer:
      return self.as_apple_container
    return super().get_capability(captype)
2 of 3
2

In order to ensure a class has some properties, I make base "interface" classes

While this is a common design pattern in statically typed languages, Python programmers consider more idiomatic to use duck typing for your classes. Since the language is dynamically typed, if you have Foo and Bar classes that both can contain bananas, you are free to call unknown.banana on a variable that can be either. If unknown can be an object that don't implement banana, you can also use getattr or try/except AttributeError blocks. The explicit interface is just bloat over features the language already support.

If for any reason you don't want to get rid of these interfaces, then you could at least use multiple inheritance. It exists because it has uses and is correct to use in many cases.

can it hit us back later with problems like method resolution order or name collisions ?

In your multiple inheritance declaration, the first object has priority when it comes to symbol collisions. In some cases, it's a feature, but you have to be careful this doesn't cause unintended overrides, like you would when defining methods and properties in a child class.

The capability suggestion is overly defensive over inheritance mechanisms. Making sure you don't accidentally override is your responsibility, but it shouldn't be a huge burden. If it happens to be one, it's likely you have other problems. And in cases you are not sure of the symbols contained in a class and want to use it as a black box, it may be appropriate to favor composition.

🌐
Dot Net Tutorials
dotnettutorials.net › home › interfaces in python
Interfaces in Python with Examples - Dot Net Tutorials
July 5, 2020 - We can create interfaces by using abstract classes which have only abstract methods. Interface can contain: ... As we know, abstract methods should be implemented in the subclass of interface (Abstract Class).