๐ŸŒ
Python
typing.python.org โ€บ en โ€บ latest โ€บ spec โ€บ protocol.html
Protocols โ€” typing documentation
The rationale for this is that the protocol class implementation is often not shared by subtypes, so the interface should not depend on the default implementation. Examples: from typing import Protocol class Template(Protocol): name: str # This is a protocol member value: int = 0 # This one too (with default) def method(self) -> None: self.temp: list[int] = [] # Error in type checker class Concrete: def __init__(self, name: str, value: int) -> None: self.name = name self.value = value def method(self) -> None: return var: Template = Concrete('value', 42) # OK
๐ŸŒ
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]. For example, IntList below is iterable, over int values:
Discussions

Protocols vs Abstract Base Classes in Python
I'm going to add that performance for protocols is bad when doing an instance check. It's O(n) where n is the size of the interface, and they're not cheap checks. For example, I improved performance in ReactPy by 50% by removing a single isinstance check against a protocol that was done every render. More on reddit.com
๐ŸŒ r/Python
31
121
December 1, 2024
How do I annotate that a python class should implement a Protocol? - Stack Overflow
If I define a Protocol and a class that implements that protocol, I would like to document that the class does/should implement the protocol so that other developers can easily see that the class is More on stackoverflow.com
๐ŸŒ stackoverflow.com
@typing.protocol decorator to create a class of type Protocol - Ideas - Discussions on Python.org
Instead of having typing.Protocol, which we inherit to define a Protocol class, we could have a global @protocol decorator that declares a class as a Protocol. And the class that adheres to that Protocol should be decorated with a decorator having the name of the Protocol class it adheres to. More on discuss.python.org
๐ŸŒ discuss.python.org
0
October 5, 2022
python - Correct way to hint that a class is implementing a Protocol? - Stack Overflow
On a path of improvement for my Python dev work. I have interest in testing interfaces defined with Protocol at CI/deb building time, so that if a interface isn't actually implemented by a class we... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Real Python
realpython.com โ€บ python-protocol
Python Protocols: Leveraging Structural Subtyping โ€“ Real Python
July 25, 2024 - For example, you can informally say that your Dog and Cat classes have a living protocol consisting of the .eat() and .drink() methods, which are the operations required to support life. You can also say that the classes have a sounding protocol comprised of the .make_sound() method. Note: In Pythonโ€™s built-in classes, youโ€™ll find many examples of classes that support multiple protocols.
๐ŸŒ
Python
peps.python.org โ€บ pep-0544
PEP 544 โ€“ Protocols: Structural subtyping (static duck typing) | peps.python.org
Variable annotation syntax was added in Python 3.6, so that the syntax for defining protocol variables proposed in specification section canโ€™t be used if support for earlier versions is needed. To define these in a manner compatible with older versions of Python one can use properties. Properties can be settable and/or abstract if needed: class Foo(Protocol): @property def c(self) -> int: return 42 # Default value can be provided for property...
๐ŸŒ
Reddit
reddit.com โ€บ r/python โ€บ protocols vs abstract base classes in python
r/Python on Reddit: Protocols vs Abstract Base Classes in Python
December 1, 2024 -

Hi everyone. Last time I shared a post about Interface programming using abs in Python, and it got a lot of positive feedbackโ€”thank you!

Several people mentioned protocols, so I wrote a new article exploring that topic. In it, I compare protocols with abstract base classes and share my thoughts and experiences with both. You can check it out here: https://www.tk1s.com/python/protocols-vs-abstract-base-classes-in-python Hope you'll like it! Thanks!

๐ŸŒ
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 - So, why is this called a โ€œprotocolโ€ and what kinds of things is it good for? Letโ€™s go deeper to answer those questions. The built-in function len() works with any object that has a __len__() method. Objects donโ€™t have to declare that they have a __len__() method or subclass any special classes to work with len(). Python programmers call this state of affairs a protocol, and the most common example is probably the iteration protocol.
๐ŸŒ
Xebia
xebia.com โ€บ home โ€บ blog โ€บ protocols in python: why you need them
Protocols In Python: Why You Need Them | Xebia
July 25, 2022 - The protocol class implementation defines rules and guidelines for implementing protocol methods within a class, including the use of variable annotations. Python Protocol class variables are defined within the class body of a protocol, and ...
๐ŸŒ
DEV Community
dev.to โ€บ shameerchagani โ€บ what-is-a-protocol-in-python-3fl1
What is a Protocol in python? - DEV Community
July 5, 2023 - A protocol is a set of methods or attributes that an object must have in order to be considered compatible with that protocol. Protocols enable you to define interfaces without explicitly creating a class or inheriting from a specific base class.
Find elsewhere
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ protocols in python
Protocols in Python | Towards Data Science
January 21, 2025 - Python 3.8 introduced a neat new feature: protocols. Protocols are an alternative to abstract base classes (ABC), and allow structural subtyping โ€“ checking whether two classes are compatible based on available attributes and functions alone.
๐ŸŒ
Auth0
auth0.com โ€บ blog โ€บ protocol-types-in-python
Protocol Types in Python 3.8
June 23, 2021 - While the concept is the same as Clojure, Python does not need explicit protocol declaration. If a type has the methods specified in the protocol, then it implements the protocol.
๐ŸŒ
Python
typing.python.org โ€บ en โ€บ latest โ€บ reference โ€บ protocols.html
Protocols and structural subtyping โ€” typing documentation
The typing module defines various protocol classes that correspond to places where duck typing is commonly used in Python, such as Iterable[T].
๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
@typing.protocol decorator to create a class of type Protocol - Ideas - Discussions on Python.org
October 5, 2022 - Instead of having typing.Protocol, which we inherit to define a Protocol class, we could have a global @protocol decorator that declares a class as a Protocol. And the class that adheres to that Protocol should be decorated with a decorator having the name of the Protocol class it adheres to.
๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ python oop โ€บ python protocol
Python Protocol - Python Tutorial
March 31, 2025 - class Item(Protocol): quantity: float price: floatCode language: Python (python)
๐ŸŒ
Medium
medium.com โ€บ @pouyahallaj โ€บ introduction-1616b3a4a637
Python Protocols vs. ABCs: A Comprehensive Comparison of Interface Design | Medium
May 29, 2023 - Protocols allow you to specify the expected methods and attributes that a class should have without requiring explicit inheritance or modifications to the class hierarchy. Letโ€™s see an example of implementing a Protocol in Python:
Top answer
1 of 1
22

When talking about static type checking, it helps to understand the notion of a subtype as distinct from a subclass. (In Python, type and class are synonymous; not so in the type system implemented by tools like mypy.)

A type T is a nominal subtype of type S if we explicitly say it is. Subclassing is a form of nominal subtyping: T is a subtype of S if (but not only if) T is a subclass of S.

A type T is a structural subtype of type S if it something about T itself is compatible with S. Protocols are Python's implementation of structure subtyping. Shape does not not need to be a nominal subtype of IShape (via subclassing) in order to be a structural subtype of IShape (via having an x attribute).

So the point of defining IShape as a Protocol rather than just a superclass of Shape is to support structural subtyping and avoid the need for nominal subtyping (and all the problems that inheritance can introduce).

class IShape(Protocol):
    x: float


# A structural subtype of IShape
# Not a nominal subtype of IShape
class Shape:
    def __init__(self):
        self.x = 3

# Not a structural subtype of IShape
class Unshapely:
    def __init__(self):
        pass


def foo(v: IShape):
    pass

foo(Shape())  # OK
foo(Unshapely())  # Not OK

So is structural subtyping a replacement for nominal subtyping? Not at all. Inheritance has its uses, but when it's your only method of subtyping, it gets used inappropriately. Once you have a distinction between structural and nominal subtyping in your type system, you can use the one that is appropriate to your actual needs.

๐ŸŒ
OneUptime
oneuptime.com โ€บ home โ€บ blog โ€บ how to use protocol classes for type safety in python
How to Use Protocol Classes for Type Safety in Python
February 2, 2026 - Protocol classes are one of Python's most powerful typing features. They let you write generic, reusable code that works with any object having the right shape, while still catching type errors before runtime.
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.

๐ŸŒ
Stephensugden
stephensugden.com โ€บ crash_into_python โ€บ Protocols.html
Protocols - Stephen Sugden
February 6, 2023 - The secret is the iteration protocol. As long as some_collection implements a couple of methods it can be used as an iterator. http://docs.python.org/library/stdtypes.html#iterator-types ยท def reverse_iter(seq): position = len(seq) - 1 while True: if position < 0: raise StopIteration yield seq[position] position -= 1 class BackwardsSequence(list): def __iter__(self): return reverse_iter(self)
๐ŸŒ
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.