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

See python/mypy#5018 for motivation.
This commit is contained in:
Ivan Levkivskyi 2019-05-12 00:18:56 +01:00 committed by GitHub
parent 58b713c4ef
commit 88135b711d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 48 additions and 0 deletions

View File

@ -762,6 +762,54 @@ aliases::
CompatReversible = Union[Reversible[T], SizedIterable[T]] 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: .. _discussion:
``@runtime_checkable`` decorator and narrowing types by ``isinstance()`` ``@runtime_checkable`` decorator and narrowing types by ``isinstance()``