gh-132493: Support deferred annotations in Protocols (#132494)

This commit is contained in:
Jelle Zijlstra 2025-04-15 10:14:27 -07:00 committed by GitHub
parent 818b6a9ead
commit 666eeda13d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 14 additions and 1 deletions

View file

@ -4554,6 +4554,15 @@ class ProtocolTests(BaseTestCase):
)
self.assertIs(type(exc.__cause__), CustomError)
def test_deferred_evaluation_of_annotations(self):
class DeferredProto(Protocol):
x: DoesNotExist
self.assertEqual(get_protocol_members(DeferredProto), {"x"})
self.assertEqual(
annotationlib.get_annotations(DeferredProto, format=annotationlib.Format.STRING),
{'x': 'DoesNotExist'}
)
class GenericTests(BaseTestCase):

View file

@ -1801,7 +1801,9 @@ def _get_protocol_attrs(cls):
for base in cls.__mro__[:-1]: # without object
if base.__name__ in {'Protocol', 'Generic'}:
continue
annotations = getattr(base, '__annotations__', {})
annotations = _lazy_annotationlib.get_annotations(
base, format=_lazy_annotationlib.Format.FORWARDREF
)
for attr in (*base.__dict__, *annotations):
if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
attrs.add(attr)

View file

@ -0,0 +1,2 @@
Support creation of :class:`typing.Protocol` classes with annotations that
cannot be resolved at class creation time.