Skip to content
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
28 changes: 27 additions & 1 deletion pep-0544.txt
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,32 @@ The self-types in protocols follow the corresponding specification
c = Other() # Also OK


Callback protocols
------------------

Protocols can be used to define flexible callback types that are hard
(or even impossible) to express using the ``Callable[...]`` syntax
specified by PEP 484, such as variadic, overloaded, and complex generic
callbacks. They can be defined as protocols with a ``__call__`` member::

from typing import Optional, List, Protocol

class Combiner(Protocol):
def __call__(self, *vals: bytes,
maxlen: Optional[int] = None) -> List[bytes]: ...

def good_cb(*vals: bytes, maxlen: Optional[int] = None) -> List[bytes]:
...
def bad_cb(*vals: bytes, maxitems: Optional[int]) -> List[bytes]:
...

comb: Combiner = good_cb # OK
comb = bad_cb # Error! Argument 2 has incompatible type because of
# different name and kind in the callback

Callback protocols and ``Callable[...]`` types can be used interchangeably.


Using Protocols
===============

Expand Down Expand Up @@ -930,7 +956,7 @@ effects on the core interpreter and standard library except in the
``typing`` module, and a minor update to ``collections.abc``:

* Define class ``typing.Protocol`` similar to ``typing.Generic``.
* Implement metaclass functionality to detect whether a class is
* Implement functionality to detect whether a class is
a protocol or not. Add a class attribute ``_is_protocol = True``
if that is the case. Verify that a protocol class only has protocol
base classes in the MRO (except for object).
Expand Down