416
public interface IInterface
{
    void show();
}

 public class MyClass : IInterface
{

    #region IInterface Members

    public void show()
    {
        Console.WriteLine("Hello World!");
    }

    #endregion
}

How do I implement Python equivalent of this C# code ?

class IInterface(object):
    def __init__(self):
        pass

    def show(self):
        raise Exception("NotImplementedException")


class MyClass(IInterface):
   def __init__(self):
       IInterface.__init__(self)

   def show(self):
       print 'Hello World!'

Is this a good idea?? Please give examples in your answers.

10
  • 1
    What would be the purpose for using an interface in your case?
    – Bandi-T
    Commented Jan 23, 2010 at 18:54
  • 89
    Frankly no purpose at all ! I just want to learn what to do when you need interfaces in python? Commented Jan 23, 2010 at 19:13
  • 36
    raise NotImplementedError is what show's body should be -- makes no sense to raise a completely generic Exception when Python defines a perfectly specific built-in one!-) Commented Jan 23, 2010 at 20:30
  • 4
    Shouldn't init call show() in IInterface (or raise the exception itself) so you can't instantiate an abstract interface? Commented Aug 20, 2017 at 7:45
  • 1
    I can see some use for this... let's say you have an object that you want to ensure has a specific signature. With duck typing you can't guarantee that the object will be of the signature that you expect. Sometimes it might be useful to enforce some typing on dynamically typed properties.
    – K-Dawg
    Commented Oct 11, 2017 at 13:10

8 Answers 8

261

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!

22
  • 18
    Could you elaborate on this? 1. How does one implement such an interface? 2. How can it be used to look up components?
    – geoidesic
    Commented May 23, 2018 at 14:26
  • 239
    "Interfaces are not necessary in Python. Except when they are." Commented Feb 9, 2019 at 18:01
  • 34
    interfaces are mostly used to have a predictable outcome / enforce correctness of members when passing objects around. it would be great if python supported this as an option. it would also allow development tools to have better intellisense
    – Sonic Soul
    Commented Mar 19, 2019 at 18:57
  • 97
    "This is because Python has proper multiple inheritance", who said interfaces are for multiple inheritance? Commented Dec 14, 2019 at 19:30
  • 29
    People talking about interfaces in terms of multiple inheritance, memory footprint: what if I have a module that abstracts the filesystem. The backend can be the local filesystem, ram, or one of the many cloud storage systems. Would be nice to instantiate a class from such module and known that the object will have certain methods, regardless of the backend implemented. IOW, interfaces. Nothing to do with multiple inheritance, nothing to do with memory. Commented Aug 23, 2020 at 1:31
201

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.)

3
  • 6
    Question: What does the module-name "ABC" stand for? Commented Jan 9, 2020 at 15:14
  • 7
    "ABC" stands for "Abstract Base Classes", see official docs
    – mrts
    Commented Jan 13, 2020 at 15:18
  • 2
    NB it's not enough to set the base class and decorate methods; the abstract methods must also raise NotImplementedError. I learned this the hard way in stackoverflow.com/a/38885553/5568265 Commented Jun 4, 2023 at 0:12
123
+50

I invite you to explore what Python 3.8 has to offer for the subject matter in form of Structural subtyping (static duck typing) (PEP 544)

See the short description https://docs.python.org/3/library/typing.html#typing.Protocol

For the simple example here it goes like this:

from typing import Protocol

class MyShowProto(Protocol):
    def show(self):
        ...


class MyClass:
    def show(self):
        print('Hello World!')


class MyOtherClass:
    pass


def foo(o: MyShowProto):
    return o.show()

foo(MyClass())  # ok
foo(MyOtherClass())  # fails

foo(MyOtherClass()) will fail static type checks:

$ mypy proto-experiment.py 
proto-experiment.py:21: error: Argument 1 to "foo" has incompatible type "MyOtherClass"; expected "MyShowProto"
Found 1 error in 1 file (checked 1 source file)

In addition, you can specify the base class explicitly, for instance:

class MyOtherClass(MyShowProto):

but note that this makes methods of the base class actually available on the subclass, and thus the static checker will not report that a method definition is missing on the MyOtherClass. So in this case, in order to get a useful type-checking, all the methods that we want to be explicitly implemented should be decorated with @abstractmethod:

from typing import Protocol
from abc import abstractmethod

class MyShowProto(Protocol):
    @abstractmethod
    def show(self): raise NotImplementedError


class MyOtherClass(MyShowProto):
    pass


MyOtherClass()  # error in type checker
5
  • how do we decorate a static method to get the same effect? Note that abstractstaticmethod is deprecated, and staticmethod does not induce a type error Commented Jul 22, 2021 at 16:49
  • 5
    Thanks for showing the new feature. Commented Nov 8, 2021 at 1:45
  • 2
    @JoeyBaruch As written in the documentation of the abc package (see docs.python.org/3/library/abc.html#abc.abstractmethod), you can combine @staticmethod with @abstractmethod to get the desired effect (the decorator @abstractmethod should be placed at the innermost level).
    – Lightspark
    Commented Mar 29, 2022 at 14:18
  • This is the best answer if you don't want the child classes to have to explicitly implement a base class. stackoverflow.com/a/66977467/733092 makes a good short introduction to Protocols for anyone who skimmed over this.
    – Noumenon
    Commented Oct 18, 2022 at 1:10
  • I'm inclined to argue that child classes should implement the new class for readability and maintainability. If the use of the function declared in the protocol and used as a parameter in another function (as in this example code) is wrapped in a try block that catches all exceptions of any type (an unfortunately common occurrence in some of the codebases I've seen), you may have a bug on your hands that's extremely difficult to isolate. Commented Jul 28, 2023 at 16:24
120

Using the abc module for abstract base classes seems to do the trick.

from abc import ABCMeta, abstractmethod

class IInterface:
    __metaclass__ = ABCMeta

    @classmethod
    def version(self): return "1.0"
    @abstractmethod
    def show(self): raise NotImplementedError

class MyServer(IInterface):
    def show(self):
        print 'Hello, World 2!'

class MyBadServer(object):
    def show(self):
        print 'Damn you, world!'


class MyClient(object):

    def __init__(self, server):
        if not isinstance(server, IInterface): raise Exception('Bad interface')
        if not IInterface.version() == '1.0': raise Exception('Bad revision')

        self._server = server


    def client_show(self):
        self._server.show()


# This call will fail with an exception
try:
    x = MyClient(MyBadServer)
except Exception as exc:
    print 'Failed as it should!'

# This will pass with glory
MyClient(MyServer()).client_show()
6
  • 49
    Yugghh, needing some module for what should be part of the language itself, or not used at all, IMO. Commented Mar 1, 2019 at 9:48
  • 2
    do you mean: if not server.version() == '1.0': raise ...? I don't realy get this line. An explaination would be welcome.
    – Skandix
    Commented Mar 18, 2019 at 17:41
  • 4
    @MikedeKlerk I couldn't agree more. Just like the Python answer to typing; I shouldn't have to import a module to declare I want a type to be a type. The response to that is typically "well Python is dynamically typed", but that isn't an excuse. Java + Groovy solve this problem. Java for the static stuff, Groovy for the dynamic stuff. Commented Jul 3, 2019 at 21:36
  • 17
    @MikedeKlerk, the abc module is indeed built-in to python. It is a little more work to set up some of these patterns because they are largely unneeded in Python due to alternative patterns that are considered 'more Pythonic'. For the vast majority of developers, it would be as you said, 'not used at all'. However, acknowledging that there are some very niche cases that truly require these interfacing capabilities, the Python creators provided an easy-to-use API to make that possible. Commented Nov 21, 2019 at 23:13
  • 1
    I'd argue that python has a policy (at least historically) of not doing stuff at the lannguage level. I don't know why, but it keeps the language a bit smaller and simpler. Even when they do have synactic magic, this is often represented as python "under the hood". (e.g. add and friends versus C++'s operator overloading). As David points out above, there is still one way to do it as abc in the standard library.
    – Att Righ
    Commented Sep 16, 2022 at 10:59
68

interface supports Python 2.7 and Python 3.4+.

To install interface you have to

pip install python-interface

Example Code:

from interface import implements, Interface

class MyInterface(Interface):

    def method1(self, x):
        pass

    def method2(self, x, y):
        pass


class MyClass(implements(MyInterface)):

    def method1(self, x):
        return x * 2

    def method2(self, x, y):
        return x + y
4
  • 22
    A major advantage of this library, IMHO, is the early failure it gives you: If your class does not correctly implement a specified interface, you get an exception as soon as the class is read in - you don't even have to use it. With Python's own abstract base class, you get the exception when you first instantiate your class, which could be much later.
    – Hans
    Commented Apr 10, 2019 at 5:51
  • 5
    It's unnecessary, ABC offers a similar, built-in functionality.
    – Daniel
    Commented Jan 9, 2020 at 23:11
  • 2
    @DanielCasares does ABC offer an actual interface or do you mean that abstract classes without state or implementations are the solution that ABC offers?
    – asaf92
    Commented Mar 6, 2020 at 13:23
  • python is so terrible that it doesnt know this at compile time. its so backward and un-safe for a modern language. its the opposite of progress actually.
    – Luke
    Commented Jul 23, 2023 at 5:11
48

There are third-party implementations of interfaces for Python (most popular is Zope's, also used in Twisted), but more commonly Python coders prefer to use the richer concept known as an "Abstract Base Class" (ABC), which combines an interface with the possibility of having some implementation aspects there too. ABCs are particularly well supported in Python 2.6 and later, see the PEP, but even in earlier versions of Python they're normally seen as "the way to go" -- just define a class some of whose methods raise NotImplementedError so that subclasses will be on notice that they'd better override those methods!-)

4
  • 4
    There are third-party implementations of interfaces for Python What does it mean? Could you please explain ABC ? Commented Jan 23, 2010 at 18:42
  • 4
    Well, I'll take issue with ABC's being "richer". ;) There are things zope.interface can do that ABC's can't as well as the other way around. But otherwise you are as usual right. +1 Commented Jan 23, 2010 at 19:26
  • 1
    @Alfred: It means that modules like zope.interface is not included in the standard library, but available from pypi. Commented Jan 23, 2010 at 19:27
  • I have still hard time to grok the concept of ABC's. Would it be possible for somebody to rewrite twistedmatrix.com/documents/current/core/howto/components.html (IMHO, an excellent explanation of the interfaces concept) in terms of ABC's. Does it make a sense?
    – mcepl
    Commented Jul 29, 2016 at 8:25
26

Something like this (might not work as I don't have Python around):

class IInterface:
    def show(self): raise NotImplementedError

class MyClass(IInterface):
    def show(self): print "Hello World!"
3
  • 4
    What should I do about __init__(self) the constructor? Commented Jan 23, 2010 at 18:39
  • 1
    Up to you. Since there is no compile-time check against constructing an object from an abstract class you would not gain any protection during coding/compiling. There will be a constructor inherited, so the object would get created, just be "empty". It is up to you to decide whether you'd be better off by allowing this to happen and catch failures later, or explicitly stop the program right then and there by implementing a similar constructor throwing an exception.
    – Bandi-T
    Commented Jan 23, 2010 at 18:45
  • 3
    That's why abc.ABC is much better than raising NotImplementedError - instantiation of an abc.ABC subclass that does not implement all the abstract methods fails early, so you are protected against errors. See my answer below for how the error looks like.
    – mrts
    Commented Jul 13, 2018 at 9:13
14

My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.

E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify action. This is checked at compile time.

In Python, there is no such thing as compile time and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify attribute.

This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.