diff --git a/pep-0544.txt b/pep-0544.txt index e75d783026e..8336b1749b5 100644 --- a/pep-0544.txt +++ b/pep-0544.txt @@ -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()``