Skip to content

PEP 544: Specify usage of modules as subtypes of protocols #646

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions pep-0544.txt
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,54 @@ aliases::
CompatReversible = Union[Reversible[T], SizedIterable[T]]


Modules as subtypes of protocols
--------------------------------

A module object is accepted where a protocol is expected if the public
interface of the given module is compatible with the expected protocol.
For example::

# 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

To determine compatibility of module level functions, the ``self`` argument
of the corresponding protocol methods is dropped. For example::

# callbacks.py
def on_error(x: int) -> None:
...
def on_success() -> None:
...

# main.py
import callbacks
from typing import Protocol

class Reporter(Protocol):
def on_error(self, x: int) -> None:
...
def on_success(self) -> None:
...

rp: Reporter = callbacks # Passes type check


.. _discussion:

``@runtime`` decorator and narrowing types by ``isinstance()``
Expand Down