I don't use mypy but I do check types in VSCode and this works for me:

from typing import Protocol

class MyType(Protocol):
    @staticmethod
    def foo() -> int:
        ...


import mymodule
# mymodule.py just contains 
# def foo() -> int:
#     return 42

def test(something: MyType):
    print(something.foo())  # prints 42

test(mymodule)  # type checking OK here!
Answer from Flávio Fonseca on Stack Overflow
🌐
Python
peps.python.org › pep-0544
PEP 544 – Protocols: Structural subtyping (static duck typing) | peps.python.org
March 5, 2017 - In this PEP we specify static and runtime semantics of protocol classes that will provide a support for structural subtyping (static duck typing). Currently, PEP 484 and the typing module [typing] define abstract base classes for several common Python protocols such as Iterable and Sized.
🌐
Python
typing.python.org › en › latest › spec › protocol.html
Protocols — typing documentation
However, it should be possible for protocol types to implement custom instance and class checks when this makes sense, similar to how Iterable and other ABCs in collections.abc and typing already do it, but this is limited to non-generic and unsubscripted generic protocols (Iterable is statically equivalent to Iterable[Any]). The typing module will define a special @runtime_checkable class decorator that provides the same semantics for class and instance checks as for collections.abc classes, essentially making them “runtime protocols”:
🌐
Mypy
mypy.readthedocs.io › en › stable › protocols.html
Protocols and structural subtyping - mypy 1.19.1 documentation
See PEP 544 for the detailed specification of protocols and structural subtyping in Python. 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 ...
🌐
Real Python
realpython.com › python-protocol
Python Protocols: Leveraging Structural Subtyping – Real Python
July 25, 2024 - Python 3.8 introduced a way to create formal protocols in the typing system. From this version on, the typing module defines a base class called Protocol that you can use to create custom protocols.
🌐
Medium
medium.com › @pouyahallaj › introduction-1616b3a4a637
Python Protocols vs. ABCs: A Comprehensive Comparison of Interface Design | Medium
May 29, 2023 - Let’s see an example of implementing a Protocol in Python: from typing import Protocol class MyProtocol(Protocol): def my_method(self): pass · In the code snippet above, we define a Protocol called MyProtocol using the Protocol base class provided by the typing module.
🌐
Python
typing.python.org › en › latest › reference › protocols.html
Protocols and structural subtyping — typing documentation
Structural subtyping can be seen as a static equivalent of duck typing, which is well known to Python programmers. See PEP 544 for the detailed specification of protocols and structural subtyping in Python. The typing module defines various protocol classes that correspond to places where duck ...
🌐
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.
Find elsewhere
🌐
Towards Data Science
towardsdatascience.com › home › latest › protocols in python
Protocols in Python | Towards Data Science
January 21, 2025 - Second, you cannot change existing ... party modules: this is a problem if you would like types imported from those to be subtypes of others, possibly in combination with other types introduced by you. And lastly, this somewhat goes against the idea of Python and duck typing. Thus, Python 3.8 introduced protocols, alleviating ...
🌐
Python Tutorial
pythontutorial.net › home › python oop › python protocol
Python Protocol - Python Tutorial
March 31, 2025 - To make the calculate_total() more dynamic while leveraging type hints, you can use the Protocol from the typing module. The Protocol class has been available since Python 3.8, described in PEP 544.
🌐
TutorialsPoint
tutorialspoint.com › python_network_programming › python_internet_protocol.htm
Python - Internet Protocol
August 1, 2021 - A program like the web browser ... categories of internet protocols. Thes protocols are created to serve the needs of different types of data communication between different computers in the internet. Python has several modules to handle each of these communication ...
🌐
Python
docs.python.org › 3 › library › internet.html
Internet Protocols and Support — Python 3.14.3 documentation
The modules described in this chapter implement internet protocols and support for related technology. They are all implemented in Python. Most of these modules require the presence of the system-dependent module socket, which is currently supported on most popular platforms.
🌐
mypy
mypy.readthedocs.io › en › latest › protocols.html
Protocols and structural subtyping - mypy 1.20.0+dev.0e6cfd41cf883acfada2ed2c72dc6f18a343bb78 documentation
See PEP 544 for the detailed specification of protocols and structural subtyping in Python. 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:
🌐
Codefellows
codefellows.github.io › sea-python-401d4 › lectures › protocols.html
Network Protocols in Python — Python 401 2.1 documentation
The modules allow you to use a Python API to interact with the protocol, so you don’t have to remember exactly how to format the messages you send.
🌐
Mimo
mimo.org › glossary › python › protocol
Python Protocol: Syntax, Usage, and Examples
Start your coding journey with Python. Learn basics, data types, control flow, and more ... Protocols live in the typing module (or typing_extensions in older versions).
🌐
PyPI
pypi.org › project › protocol
protocol · PyPI
Tags protocol · Requires: Python ... :: 3.11 · Report project as malware · Library and utilities to develop protocols and check for protocol compliance in medical imaging....
      » pip install protocol
    
Published   Mar 08, 2024
Version   0.37
🌐
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.
🌐
GitHub
github.com › python › mypy › issues › 5018
Allow using modules as subtypes of protocols · Issue #5018 · python/mypy
July 5, 2020 - # file default_config.py timeout = 100 one_flag = True other_flag = False # file __main__.py import default_config from typing import Protocol class Options(Protocol): timeout: int one_flag: bool other_flag: bool def setup(options: Options) -> None: ... setup(default_config) # OK · This will allow better typing than just types.ModuleType and should be straightforward to implement.
Published   May 10, 2018
Author   ilevkivskyi
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.

🌐
GitHub
github.com › modelcontextprotocol › python-sdk
GitHub - modelcontextprotocol/python-sdk: The official Python SDK for Model Context Protocol servers and clients · GitHub
The official Python SDK for Model Context Protocol servers and clients - modelcontextprotocol/python-sdk
Starred by 22.3K users
Forked by 3.2K users
Languages   Python