PEP 746: Apply comments from review (#3802)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
Adrian Garcia Badaracco 2024-06-05 18:22:37 -05:00 committed by GitHub
parent 46e2cf7169
commit 8a3d3f0f4a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 13 additions and 7 deletions

View File

@ -43,17 +43,23 @@ This use case comes up in libraries like :pypi:`pydantic`, which use
Specification Specification
============= =============
This PEP introduces a protocol that can be used by static and runtime type checkers to validate
This PEP introduces a new ``__supports_type__`` protocol that both static and the consistency between ``Annotated`` metadata and a given type.
runtime type checkers can use to understand if a metadata object in Objects that implement this protocol have a method named ``__supports_type__``
``Annotated`` is valid for the given type. Objects that implement this protocol that takes a single positional argument and returns ``bool``::
must have a method named ``__supports_type__`` that takes a single positional argument and
returns ``bool``::
class Int64: class Int64:
def __supports_type__(self, obj: int) -> bool: def __supports_type__(self, obj: int) -> bool:
return isinstance(obj, int) return isinstance(obj, int)
The protocol being introduced would be defined as follows if it were to be defined in code form::
from typing import Protocol
class SupportsType[T](Protocol):
def __supports_type__(self, obj: T, /) -> bool:
...
When a static type checker encounters a type expression of the form ``Annotated[T, M1, M2, ...]``, When a static type checker encounters a type expression of the form ``Annotated[T, M1, M2, ...]``,
it should enforce that for each metadata element in ``M1, M2, ...``, one of the following is true: it should enforce that for each metadata element in ``M1, M2, ...``, one of the following is true:
@ -79,7 +85,7 @@ For example, to support a generic ``Gt`` metadata, one might write::
def __init__(self, value: T) -> None: def __init__(self, value: T) -> None:
self.value = value self.value = value
def __supports_type__(self, obj: SupportsGt[T]) -> bool: def __supports_type__(self, obj: SupportsGt[T], /) -> bool:
return obj > self.value return obj > self.value
x1: Annotated[int, Gt(0)] = 1 # OK x1: Annotated[int, Gt(0)] = 1 # OK