PEP 746: Apply comments from review (#3802)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
parent
46e2cf7169
commit
8a3d3f0f4a
|
@ -43,17 +43,23 @@ This use case comes up in libraries like :pypi:`pydantic`, which use
|
|||
|
||||
Specification
|
||||
=============
|
||||
|
||||
This PEP introduces a new ``__supports_type__`` protocol that both static and
|
||||
runtime type checkers can use to understand if a metadata object in
|
||||
``Annotated`` is valid for the given type. Objects that implement this protocol
|
||||
must have a method named ``__supports_type__`` that takes a single positional argument and
|
||||
returns ``bool``::
|
||||
This PEP introduces a protocol that can be used by static and runtime type checkers to validate
|
||||
the consistency between ``Annotated`` metadata and a given type.
|
||||
Objects that implement this protocol have a method named ``__supports_type__``
|
||||
that takes a single positional argument and returns ``bool``::
|
||||
|
||||
class Int64:
|
||||
def __supports_type__(self, obj: int) -> bool:
|
||||
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, ...]``,
|
||||
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:
|
||||
self.value = value
|
||||
|
||||
def __supports_type__(self, obj: SupportsGt[T]) -> bool:
|
||||
def __supports_type__(self, obj: SupportsGt[T], /) -> bool:
|
||||
return obj > self.value
|
||||
|
||||
x1: Annotated[int, Gt(0)] = 1 # OK
|
||||
|
|
Loading…
Reference in New Issue