PEP 544: Specify usage of modules as subtypes of protocols (#646)
See python/mypy#5018 for motivation.
This commit is contained in:
parent
58b713c4ef
commit
88135b711d
48
pep-0544.txt
48
pep-0544.txt
|
@ -762,6 +762,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_checkable`` decorator and narrowing types by ``isinstance()``
|
||||
|
|
Loading…
Reference in New Issue