Skip to content

gh-132493: Support deferred annotations in Protocols #132494

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 15, 2025
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4554,6 +4554,15 @@ class Commentable(Protocol):
)
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(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: when should we test all formats and when just one is enough?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess in this case Protocol is not doing anything very sophisticated with its annotations, so we can just run a basic test to make sure it works.

annotationlib.get_annotations(DeferredProto, format=annotationlib.Format.STRING),
{'x': 'DoesNotExist'}
)


class GenericTests(BaseTestCase):

Expand Down
4 changes: 3 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Support creation of :class:`typing.Protocol` classes with annotations that
cannot be resolved at class creation time.
Loading