From 55e12994a02a0a67860e1389bffceb5e8b2ca387 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Thu, 23 May 2019 22:55:07 +0100 Subject: [PATCH 1/2] Couple final edits to PEP 544 --- pep-0544.txt | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/pep-0544.txt b/pep-0544.txt index 9476121731e..cd8e330fd39 100644 --- a/pep-0544.txt +++ b/pep-0544.txt @@ -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. For example, 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 =============== @@ -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). From 59b78521f268091f7bc62a86df0d01f55710a242 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Thu, 23 May 2019 22:11:38 -0700 Subject: [PATCH 2/2] Fix sentence fragment Co-Authored-By: Jelle Zijlstra --- pep-0544.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pep-0544.txt b/pep-0544.txt index cd8e330fd39..831ff62765a 100644 --- a/pep-0544.txt +++ b/pep-0544.txt @@ -616,7 +616,7 @@ 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. For example, variadic, overloaded, and complex generic +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