Skip to content

gh-132493: lazy evaluation of annotations in typing._proto_hook #132534

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
Show file tree
Hide file tree
Changes from 6 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
22 changes: 22 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4554,6 +4554,28 @@ class Commentable(Protocol):
)
self.assertIs(type(exc.__cause__), CustomError)

def test_isinstance_with_deferred_evaluation_of_annotations(self):
@runtime_checkable
class P(Protocol):
x: undefined | int
def meth(self):
...

class DeferredClass:
x: undefined

class DeferredClassImplementingP:
x: undefined | int

def __init__(self):
self.x = 0

def meth(self):
...

self.assertFalse(isinstance(DeferredClass(), P))
self.assertTrue(isinstance(DeferredClassImplementingP(), P))

Copy link
Member

Choose a reason for hiding this comment

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

Also add a test with a class that does fulfill the protocol.

Also, please add a NEWS entry.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added a class that satisfies the protocol and a NEWS entry:)


class GenericTests(BaseTestCase):

Expand Down
10 changes: 5 additions & 5 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1801,7 +1801,7 @@ 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 Expand Up @@ -2018,10 +2018,10 @@ def _proto_hook(cls, other):
break

# ...or in annotations, if it is a sub-protocol.
annotations = getattr(base, '__annotations__', {})
if (isinstance(annotations, collections.abc.Mapping) and
attr in annotations and
issubclass(other, Generic) and getattr(other, '_is_protocol', False)):
annotations = _lazy_annotationlib.get_annotations(base, format=_lazy_annotationlib.Format.FORWARDREF)
if (attr in annotations
and issubclass(other, Generic)
and getattr(other, '_is_protocol', False)):
Copy link
Member

Choose a reason for hiding this comment

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

We can probably gain some performance by doing the issubclass() and getattr() checks before doing the annotations check, since they should be fast and for most use cases they'll return False (it's surely more common to do isinstance(<non protocol>, Protocol), not isinstance(<other protocol>, Protocol)).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I moved the issubclass() and geattr() checks up:)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

With the new order of conditions we could also move the call to _lazy_annotationlib.get_annotations so we only do that in case the other two conditions are true, what do you think?
Like this:

    if (
        issubclass(other, Generic)
        and getattr(other, "_is_protocol", False)
        and attr in _lazy_annotationlib.get_annotations(base, format=_lazy_annotationlib.Format.FORWARDREF)
    ):

break
else:
return NotImplemented
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:class:`typing.Protocol` now uses :func:`annotationlib.get_annotations` when
checking whether or not an instance implements the protocol with
:func:`isinstance`. This enables support for ``isinstance`` checks against
classes with deferred annotations.
Loading