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
🌐
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.
🌐
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.
Discussions

Interfaces with Protocols: why not ditch ABC for good?
Whereas with Protocols it's gonna be ( good tutorial ): I think that is not a good example of how to write programs. What he did by having protocols I would have done by using mixins. The way that I see objects is that they have various capabilities that can be mixed in. multiple inheritance in python would have been a much better way to implement that example in my opinion. I would also say that the author of this tutorial needs to learn a thing or 2 about an inversion of control and dependency injection. The author basically sets up a straw man problem and then solves his straw man problem. He had no business creating instances of the object outside of the class itself. If he had simply called a constructor methods within the classes then the other class wouldn't have been attempting to make instances of those other classes. More on reddit.com
🌐 r/Python
34
63
January 22, 2023
Python terminology: interface vs. protocol - Stack Overflow
Can someone explain the difference between the terms protocol and interface in the context of Python programming? I'm seeing references to the term "protocol" in things like the buffer pr... More on stackoverflow.com
🌐 stackoverflow.com
Python Interfaces: Choose Protocols Over ABC
Protocols and abstract classes are not interchangeable. You cannot simply choose one over the other. There is a substantial difference: abstract class ensures that an implementation meets certain requirements when a subclass is declared, while protocol checks if an instance meets certain requirements when it's being used. They are different in the same way as "They are of the same kind" and "There are things that both of them can do". Please, don't confuse people with such articles. More on reddit.com
🌐 r/Python
20
64
February 12, 2023
Inheritance, Interfaces, Protocols and static type analysis in Python confusion
abstract methods can be implemented without importing @abstractmethod if you just make the method raise a NotImplementedError. Of course, importing the ABC baseclass has another benefit in exceptions can be caught at instantiation time rather than call time. More on reddit.com
🌐 r/Python
14
16
May 2, 2022
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.

🌐
Real Python
realpython.com › python-protocol
Python Protocols: Leveraging Structural Subtyping – Real Python
July 25, 2024 - In this tutorial, you'll learn about Python's protocols and how they can help you get the most out of using Python's type hint system and static type checkers.
🌐
Python
peps.python.org › pep-0544
PEP 544 – Protocols: Structural subtyping (static duck typing) | peps.python.org
March 5, 2017 - Type hints introduced in PEP 484 can be used to specify type metadata for static type checkers and other third party tools. However, PEP 484 only specifies the semantics of nominal subtyping. In this PEP we specify static and runtime semantics of protoc...
🌐
Python Tutorial
pythontutorial.net › home › python oop › python protocol
Python Protocol - Python Tutorial
March 31, 2025 - In this tutorial, you'll learn about the Python Protocol and its use to define implicit interfaces.
Find elsewhere
🌐
Mypy
mypy.readthedocs.io › en › stable › protocols.html
Protocols and structural subtyping - mypy 1.19.1 documentation
The collections.abc, typing and other stdlib modules define various protocol classes that correspond to common Python protocols, such as Iterable[T]. If a class defines a suitable __iter__ method, mypy understands that it implements the iterable protocol and is compatible with Iterable[T]. ...
🌐
Medium
medium.com › @pouyahallaj › introduction-1616b3a4a637
Python Protocols vs. ABCs: A Comprehensive Comparison of Interface Design | Medium
May 29, 2023 - Unlocking the Power of Interface Design in Python: A Comprehensive Comparison of Protocols and ABCs
🌐
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 - This guide explores these powerful abstraction mechanisms in Python, offering practical examples, detailed implementation patterns, and best practices to help you design more maintainable and robust software architectures. In classical object-oriented programming languages like Java or C#, an interface is a formal contract that specifies methods a class must implement.
🌐
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.
🌐
Krython
krython.com › tutorial › python › interfaces-in-python-protocol-classes
📘 Interfaces in Python: Protocol Classes - Tutorial | Krython
Master interfaces in python: protocol classes in Python with practical examples, best practices, and real-world applications 🚀 ... Welcome to this exciting tutorial on Protocol Classes in Python!
🌐
DEV Community
dev.to › shameerchagani › what-is-a-protocol-in-python-3fl1
What is a Protocol in python? - DEV Community
July 5, 2023 - To conclude with,Protocols provide a way to define structural typing in Python, allowing you to create interfaces without the need for explicit inheritance.
🌐
O'Reilly
oreilly.com › library › view › fluent-python › 9781491946237 › ch11.html
11. Interfaces: From Protocols to ABCs - Fluent Python [Book]
Get full access to Fluent Python and 60K+ other titles, with a free 10-day trial of O'Reilly. There are also live events, courses curated by job role, and more. ... Interfaces are the subject of this chapter: from the dynamic protocols that are the hallmark of duck typing to abstract base classes (ABCs) that make interfaces explicit and verify implementations for conformance.
🌐
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 :)

Capability ABC Protocols
Runtime checking 1 1 (with a decorator)
Static checking with mypy 1 1
Explicit interface (class Dog(Animal):) 1 1
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 interface 0 1
Number of code lines -1 (requires ABC inheritance and abstracmethod for every method) 0 (optionalProtocol inheritance)
Total score 1.5 4

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.

🌐
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.
🌐
YouTube
youtube.com › arjancodes
Protocols vs ABCs in Python - When to Use Which One? - YouTube
💡 Learn how to design great software in 7 steps: https://arjan.codes/designguide.In this video, I’m revisiting Protocols and ABCs in Python, essential for c...
Published   March 29, 2024
Views   41K
🌐
Sarahabd
sarahabd.com › sarah abderemane's website › til › python protocol typing
TIL: python Protocol and typing
December 18, 2024 - Protocol was created in Python 3.8 with the PEP 544. There a multiple protocols in python but the one I’m talking about is a way to define structural typing. Some of you will also call that implicit interface. We can use the Protocol class from the typing module.
🌐
Real Python
realpython.com › python-interface
Implementing an Interface in Python – Real Python
February 21, 2024 - In this tutorial, you'll explore how to use a Python interface. You'll come to understand why interfaces are so useful and learn how to implement formal and informal interfaces in Python.
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).