Skip to content

Commit 88135b7

Browse files
authored
PEP 544: Specify usage of modules as subtypes of protocols (#646)
See python/mypy#5018 for motivation.
1 parent 58b713c commit 88135b7

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

pep-0544.txt

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,54 @@ aliases::
762762
CompatReversible = Union[Reversible[T], SizedIterable[T]]
763763

764764

765+
Modules as subtypes of protocols
766+
--------------------------------
767+
768+
A module object is accepted where a protocol is expected if the public
769+
interface of the given module is compatible with the expected protocol.
770+
For example::
771+
772+
# file default_config.py
773+
timeout = 100
774+
one_flag = True
775+
other_flag = False
776+
777+
# file main.py
778+
import default_config
779+
from typing import Protocol
780+
781+
class Options(Protocol):
782+
timeout: int
783+
one_flag: bool
784+
other_flag: bool
785+
786+
def setup(options: Options) -> None:
787+
...
788+
789+
setup(default_config) # OK
790+
791+
To determine compatibility of module level functions, the ``self`` argument
792+
of the corresponding protocol methods is dropped. For example::
793+
794+
# callbacks.py
795+
def on_error(x: int) -> None:
796+
...
797+
def on_success() -> None:
798+
...
799+
800+
# main.py
801+
import callbacks
802+
from typing import Protocol
803+
804+
class Reporter(Protocol):
805+
def on_error(self, x: int) -> None:
806+
...
807+
def on_success(self) -> None:
808+
...
809+
810+
rp: Reporter = callbacks # Passes type check
811+
812+
765813
.. _discussion:
766814

767815
``@runtime_checkable`` decorator and narrowing types by ``isinstance()``

0 commit comments

Comments
 (0)