New in Python 3.8:

Some of the benefits of interfaces and protocols are type hinting during the development process using tools built into IDEs and static type analysis for detection of errors before runtime. This way, a static analysis tool can tell you when you check your code if you're trying to access any members that are not defined on an object, instead of only finding out at runtime.

The typing.Protocol class was added to Python 3.8 as a mechanism for "structural subtyping." The power behind this is that it can be used as an implicit base class. That is, any class that has members that match the Protocol's defined members is considered to be a subclass of it for purposes of static type analysis.

The basic example given in PEP 544 shows how this can be used.

Copyfrom typing import Protocol

class SupportsClose(Protocol):
    def close(self) -> None:
        # ...

class Resource:
    # ...
    def close(self) -> None:
        self.file.close()
        self.lock.release()

def close_all(things: Iterable[SupportsClose]) -> None:
    for thing in things:
        thing.close()

file = open('foo.txt')
resource = Resource()
close_all([file, resource])  # OK!
close_all([1])     # Error: 'int' has no 'close' method

Note: The typing-extensions package backports typing.Protocol for Python 3.5+.

Answer from gooberwonder on Stack Overflow
Top answer
1 of 8
65

New in Python 3.8:

Some of the benefits of interfaces and protocols are type hinting during the development process using tools built into IDEs and static type analysis for detection of errors before runtime. This way, a static analysis tool can tell you when you check your code if you're trying to access any members that are not defined on an object, instead of only finding out at runtime.

The typing.Protocol class was added to Python 3.8 as a mechanism for "structural subtyping." The power behind this is that it can be used as an implicit base class. That is, any class that has members that match the Protocol's defined members is considered to be a subclass of it for purposes of static type analysis.

The basic example given in PEP 544 shows how this can be used.

Copyfrom typing import Protocol

class SupportsClose(Protocol):
    def close(self) -> None:
        # ...

class Resource:
    # ...
    def close(self) -> None:
        self.file.close()
        self.lock.release()

def close_all(things: Iterable[SupportsClose]) -> None:
    for thing in things:
        thing.close()

file = open('foo.txt')
resource = Resource()
close_all([file, resource])  # OK!
close_all([1])     # Error: 'int' has no 'close' method

Note: The typing-extensions package backports typing.Protocol for Python 3.5+.

2 of 8
21

In short, you probably don't need to worry about it at all. Since Python uses duck typing - see also the Wikipedia article for a broader definition - if an object has the right methods, it will simply work, otherwise exceptions will be raised.

You could possibly have a Piece base class with some methods throwing NotImplementedError to indicate they need to be re-implemented:

Copyclass Piece(object):

    def move(<args>):
        raise NotImplementedError(optional_error_message) 

class Queen(Piece):

    def move(<args>):
        # Specific implementation for the Queen's movements

# Calling Queen().move(<args>) will work as intended but 

class Knight(Piece):
    pass

# Knight().move() will raise a NotImplementedError

Alternatively, you could explicitly validate an object you receive to make sure it has all the right methods, or that it is a subclass of Piece by using isinstance or isubclass. Note that checking the type may not be considered "Pythonic" by some and using the NotImplementedError approach or the abc module - as mentioned in this very good answer - could be preferable.

Your factory just has to produce instances of objects having the right methods on them.

🌐
Andrewbrookins
andrewbrookins.com › technology › building-implicit-interfaces-in-python-with-protocol-classes
Building Implicit Interfaces in Python with Protocol Classes – Andrew Brookins
July 5, 2020 - Protocol classes allow us to define an interface, called a protocol, and use static type-checking via mypy to verify that objects satisfy the interface – without classes having to declare that they satisfy the interface or subclass anything.
🌐
Reddit
reddit.com › r/python › interfaces with protocols: why not ditch abc for good?
r/Python on Reddit: Interfaces with Protocols: why not ditch ABC for good?
January 22, 2023 -

Hello, if one finds interfaces useful in Python (>=3.8) and is convinced that static type-checking is a must, then why not ditch ABC and always use Protocols? I understand that the fundamental idea of a protocol is slightly different from an interface, but in practice, I had great success replacing abc's with Protocols without regrets.

With abc you would write (https://docs.python.org/3/library/abc.html) :

from abc import ABC, abstractmethod

class Animal(ABC):
   @abstractmethod
   def eat(self, food) -> float:
       pass

Whereas with Protocols it's gonna be (good tutorial):

from typing import Protocol

class Animal(Protocol):
   def eat(self, food) -> float:
       ...

Scores in my subjective scoring system :)

CapabilityABCProtocols
Runtime checking11 (with a decorator)
Static checking with mypy11
Explicit interface (class Dog(Animal):)11
Implicit interface with duck-typing (class Dog:)0.5 (kind of with register, but it doesn't work with mypy yet)1
Default method implementation (def f(self): return 5)-1 (implementations shouldn't be in the interfaces)-1 (same, and mypy doesn't catch this)
Callback interface01
Number of code lines-1 (requires ABC inheritance and abstracmethod for every method)0 (optionalProtocol inheritance)
Total score1.54

So I do not quite see why one should ever use ABC except for legacy reasons. Other (IMHO minor) points in favour of ABC I've seen were about interactions with code editors.

Did I miss anything?

I put more detailed arguments into a Medium. There are many tutorials on using Protocols, but not many on ABC vs Protocols comparisons. I found a battle of Protocols vs Zope, but we are not using Zope, so it's not so relevant.

🌐
Real Python
realpython.com › python-protocol
Python Protocols: Leveraging Structural Subtyping – Real Python
July 25, 2024 - In this example, you’ve used an ABC and inheritance to enforce a specific interface in a group of classes. However, sometimes it’s desirable to have a similar result without inheritance. That’s when you can use a protocol: Python shapes_v2.py · from math import pi from typing import Protocol class Shape(Protocol): def get_area(self) -> float: ...
🌐
Python
typing.python.org › en › latest › spec › protocol.html
Protocols — typing documentation
Type checkers should reject an isinstance() or issubclass() call, if there is an unsafe overlap between the type of the first argument and the protocol. Type checkers should be able to select a correct element from a union after a safe isinstance() or issubclass() call. For narrowing from non-union types, type checkers can use their best judgement (this is intentionally unspecified, since a precise specification would require intersection types). ... © Copyright 2021, The Python Typing Team.
🌐
GitConnected
levelup.gitconnected.com › python-interfaces-choose-protocols-over-abc-3982e112342e
Python interfaces: abandon ABC and switch to Protocols | by Oleg Sinavski | Level Up Coding
January 19, 2023 - Also, there are more custom packages and tutorials on the web on how to make an interface system yourself (see example). ... from typing import Protocol class Animal(Protocol): def eat(self, food) -> float: ... def sleep(self, hours) -> float: ... A protocol is a formalization of Python’s “duck-typing” ideology.
🌐
Sinavski
sinavski.com › home › interfaces abc vs. protocols
Interfaces: abc vs. Protocols - Oleg Sinavski
August 1, 2021 - Also, there are more custom packages and tutorials on the web on how to make an interface system yourself (see example). ... from typing import Protocol class Animal(Protocol): def eat(self, food) -> float: ... def sleep(self, hours) -> float: ... A protocol is a formalization of Python’s “duck-typing” ideology.
Find elsewhere
Top answer
1 of 1
6

Before I attempt to answer this question, recall the definition of interfaces:

An interface contains definitions for a group of related functionalities that a non-abstract class or a struct must implement.

Source: Microsoft Docs

Interfaces are used in statically typed languages to describe that two independent objects "implement the same behaviour". The interfaces are formally declared in code and enforced by the compiler (hence the must in the definition of interfaces above). They are one way of telling the type system that two objects can theoretically be substituted for each other (and are therefore related in a way). The other way is inheritance. If they cannot, the compiler throws an error.

Opposing to that, dynamically typed languages like Python do not require mechanisms like interfaces or inheritance to check if two objects are related. They use duck typing where the search for the appropriate function/method of an object is deduced at runtime. If found, it is executed - if not, an error is thrown. Therefore, interfaces are not required. Instead, there are so called "special methods" that can be implemented by classes to give instances certain "features", e.g. they can be hashed by implementing the __eq__ and __hash__ methods. These informal interfaces are NOT enforced by the compiler and only exist in the documentation.

To give an example for these informal interfaces, just imagine stumbling across some piece of code that implements a custom class that behaves like a list. Even though nowhere in code is this class related to any abstract sequence class, you know that it is used to produce sequence-like objects because it implements the __len__ and __getitem__ special methods.

I view protocols as much less strict version of interfaces in that they are not enforced and not all of them have to be implemented by a class. If you just want the class to be iterable, you can pick and implement the special methods that you have to implement and leave the rest of them untouched.

That being said, you can emulate interface-like behavior by using abstract base classes (ABCs).

🌐
Python
peps.python.org › pep-0544
PEP 544 – Protocols: Structural subtyping (static duck typing) | peps.python.org
March 5, 2017 - The possibility to use protocols in the runtime context as ABCs is rather a minor bonus that exists mostly to provide a seamless transition for projects that already use ABCs. Before describing the actual specification, we review and comment on existing approaches related to structural subtyping in Python and other languages: zope.interface [zope-interfaces] was one of the first widely used approaches to structural subtyping in Python.
🌐
Medium
medium.com › @pouyahallaj › introduction-1616b3a4a637
Python Protocols vs. ABCs: A Comprehensive Comparison of Interface Design | Medium
May 29, 2023 - Abstract Base Classes (ABCs) in Python provide a mechanism for defining interfaces. An interface defines a set of methods that a class must implement to be considered compatible with that interface.
🌐
Medium
aignishant.medium.com › the-ultimate-guide-to-interfaces-protocols-and-abcs-in-python-8a991d7a4430
The Ultimate Guide to Interfaces, Protocols, and ABCs in Python | by Nishant Gupta | Medium
March 6, 2025 - Python’s flexible approach to object-oriented programming offers multiple mechanisms for creating abstract interfaces and enforcing consistent behavior across classes. Three key concepts — interfaces, protocols, and Abstract Base Classes (ABCs) — provide different ways to establish contracts and shared behaviors in your code.
🌐
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.
🌐
Twistedmatrix
glyph.twistedmatrix.com › 2021 › 03 › interfaces-and-protocols.html
Interfaces and Protocols - Deciphering Glyph - Twisted
March 15, 2021 - Thanks to Shoobx, there’s a fairly actively maintained Mypy plugin that supports zope.interface which you can use to statically check your Interfaces. However, this plugin does have a few key limitations as of this writing (Again, March 2021), which makes its safety guarantees a bit lower-quality than Protocol. The net result of this is that Protocols have the “home-field advantage” in most cases; out of the box, they’ll work more smoothly with your existing editor / linter setup, and as long as your project supports Python 3.6+, at worst (if you can’t use Python 3.7, where Protocol is built in to typing) you have to take a type-check-time dependency on the typing_extensions package, whereas with zope.interface you’ll need both the run-time dependency of zope.interface itself and the Mypy plugin at type-checking time.
🌐
Romerogabriel
romerogabriel.github.io › mastering-python › classes_objects › interfaces_protocols_abc
Interfaces, Protocols, and ABCs - Mastering Python
March 31, 2025 - Static protocols can be verified by static type checkers, which is not possible for dynamic protocols. Python offers another explicit means of defining an interface in code: the abstract base class (ABC).
🌐
Hacker News
news.ycombinator.com › item
Interfaces and Protocols in Python | Hacker News
March 20, 2021 - Highly recommend reading: · https://www.python.org/dev/peps/pep-0544/
🌐
Medium
medium.com › @kandemirozenc › understanding-interfaces-abc-protocol-and-duck-typing-in-python-866ca32ab2a0
Understanding Interfaces, ABC, Protocol and Duck Typing in Python | by kandemirozenc | Medium
December 7, 2024 - Introduced in Python 3.8, Protocol provides a lightweight and flexible way to define expected behaviors. Unlike abc, Protocols do not enforce method implementation at runtime.
🌐
Python Tutorial
pythontutorial.net › home › python oop › python protocol
Python Protocol - Python Tutorial
November 14, 2025 - In this tutorial, you'll learn about the Python Protocol and its use to define implicit interfaces.
🌐
Echo $Musings
hongzhucui.com › posts › python interface and protocol
Python interface and protocol | Echo $Musings
August 22, 2024 - However, Python supports the concept of interfaces and similar functionality through other means. abstract base classes (ABCs) can be used as interfaces by defining methods that subclasses are required to implement. Also, Python 3.8 introduced protocols (via the typing module), which provide a more flexible approach to defining interfaces.
🌐
Idego Group
idego-group.com › other › we need to talk about protocols in python
We need to talk about Protocols in Python | Idego Group
February 22, 2023 - It means that if two objects have the same methods and attributes, Python will treat them as the same type. For comparison, ABCs use nominal typing, where object relationship is defined by inheritance stated deliberately in our class definition (e.g. class B(A)). Protocols are, therefore, interfaces which help define what is expected as an input of our methods.