Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-131798: JIT: Narrow the return type ofisinstance for some known arguments#133172

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
brandtbucher merged 17 commits intopython:mainfromtomasr8:jit-isinstance
May 19, 2025

Conversation

tomasr8
Copy link
Member

@tomasr8tomasr8 commentedApr 29, 2025
edited by bedevere-appbot
Loading

In this PR:

  • narrowsisintance(obj, cls) toTrue if obj is a known type and cls is a known class and obj is a subclass of cls (and vice versa forFalse)
  • in all other cases narrowsisinstance tobool.

Brandt also suggested adding an optimization for tuples which I'd like to add in a followup in order to keep the sizes of the individual PRs smaller. Though if you prefer to have it in one PR I can do it as well :)

// isinstance(obj, cls) where both obj and cls have known types
// We can deduce either True or False
PyTypeObject *inst_type = sym_get_type(inst_sym);
if (sym_matches_type(inst_sym, cls) || PyType_IsSubtype(inst_type, cls)) {
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

This simulatesPyObject_TypeCheck

Copy link
Member

Choose a reason for hiding this comment

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

Can you add a comment to that effect? :)

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Added!

@@ -886,6 +886,44 @@ dummy_func(void) {
}
}

op(_CALL_ISINSTANCE, (callable, self_or_null, args[oparg] -- res)) {
if (sym_is_null(self_or_null) || sym_is_not_null(self_or_null)) {
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

I've seen this guard used elsewhere withself_or_null but it's not clear to me whether it is needed here as well?

Copy link
Member

Choose a reason for hiding this comment

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

Yep. It's just a (weird) way of saying "we know whether it'sNULL or not". Maybe it's worth adding a helper function (in another PR) to make it clearer, since the meaning is super subtle.

tomasr8 reacted with thumbs up emoji
Copy link
Member

@brandtbucherbrandtbucher left a comment

Choose a reason for hiding this comment

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

Cool! Can you also add a test where the secondisinstance arg is a class with a metaclass defining__instancecheck__?

classEvenNumberMeta(type):def__instancecheck__(self,number):returnnotnumber%2classEvenNumber(metaclass=EvenNumberMeta):pass# Optimizer only narrows to bool, runtime value is True:even=isinstance(42,EvenNumber)

Comment on lines 1996 to 2008
class Foo:
bar = 42

x = 0
for _ in range(n):
# we only know bar (LOAD_ATTR) is not null (set via sym_new_not_null)
bar = Foo.bar
# This will only narrow to bool and not to True due to 'bar' having
# unknown (non-null) type
y = isinstance(bar, int)
if y:
x += 1
return x
Copy link
Member

Choose a reason for hiding this comment

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

This is pretty fragile: the class attr lookup is cached in the bytecode, and I actually have a branch I'll open a PR with soon that teaches the optimizer to read these caches.

So instead, let's use everyone's favorite optimization-breaker:

Suggested change
classFoo:
bar=42
x=0
for_inrange(n):
# we only know bar (LOAD_ATTR) is not null (set via sym_new_not_null)
bar=Foo.bar
# This will only narrow to bool and not to True due to 'bar' having
# unknown (non-null) type
y=isinstance(bar,int)
ify:
x+=1
returnx
x=0
for_inrange(n):
# The optimizer doesn't know the return type here:
bar=eval("42")
# This will only narrow to bool:
y=isinstance(bar,int)
ify:
x+=1
returnx

tomasr8 reacted with thumbs up emoji
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Nice trick to useeval! I updated the test :)

@@ -886,6 +886,44 @@ dummy_func(void) {
}
}

op(_CALL_ISINSTANCE, (callable, self_or_null, args[oparg] -- res)) {
if (sym_is_null(self_or_null) || sym_is_not_null(self_or_null)) {
Copy link
Member

Choose a reason for hiding this comment

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

Yep. It's just a (weird) way of saying "we know whether it'sNULL or not". Maybe it's worth adding a helper function (in another PR) to make it clearer, since the meaning is super subtle.

tomasr8 reacted with thumbs up emoji
// isinstance(obj, cls) where both obj and cls have known types
// We can deduce either True or False
PyTypeObject *inst_type = sym_get_type(inst_sym);
if (sym_matches_type(inst_sym, cls) || PyType_IsSubtype(inst_type, cls)) {
Copy link
Member

Choose a reason for hiding this comment

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

Can you add a comment to that effect? :)

Comment on lines 911 to 925
}
else {
// isinstance(obj, cls) where obj has unknown type
res = sym_new_type(ctx, &PyBool_Type);
}
}
else {
// isinstance(obj, cls) where cls has unknown type
res = sym_new_type(ctx, &PyBool_Type);
}
}
else {
res = sym_new_type(ctx, &PyBool_Type);
}
}
Copy link
Member

Choose a reason for hiding this comment

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

You can avoid all of this repetition by doing an unconditionalres = sym_new_type(ctx, &PyBool_Type); at the top, and usingsym_set_const(ctx, ...) to narrow it when possible.

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Yup that is way better, updated!

@bedevere-app
Copy link

A Python core developer has requested some changes be made to your pull request before we can consider merging it. If you could please address their requests along with any other requests in other reviews from core developers that would be appreciated.

Once you have made the requested changes, please leave a comment on this pull request containing the phraseI have made the requested changes; please review again. I will then notify any core developers who have left a review that you're ready for them to take another look at this pull request.

@tomasr8
Copy link
MemberAuthor

(Marking as draft until#133339 is merged which will let us simplify the oparg logic)

@tomasr8
Copy link
MemberAuthor

I think I addressed all your points. I also added the test you suggested. I'm planning to add support for tuples (e.g.isinstance(foo, (int, str)) in a followup so for now it just supports single types.

@tomasr8tomasr8 marked this pull request as ready for reviewMay 9, 2025 20:46
@tomasr8tomasr8 requested a review frombrandtbucherMay 9, 2025 20:47
Copy link
Member

@brandtbucherbrandtbucher left a comment

Choose a reason for hiding this comment

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

Thanks! Just one suggestion, then we can land it.

tomasr8and others added3 commitsMay 19, 2025 15:37
@Fidget-Spinner
Copy link
Member

This LGTM. A side note: on PyPy, they can actually narrowisinstance(x, cls) to subtype ofcls or even better. I wonder if we can do that? Not sure if it's safe to do so though due to subclassing rules and all that.

@brandtbucher
Copy link
Member

Yeah, could be cool. It's not really useful to us right now, since all of our guards are against exact types/versions, not many subclass checks.

@brandtbucher
Copy link
Member

CI failures are unrelated.

@brandtbucherbrandtbucher merged commit8d490b3 intopython:mainMay 19, 2025
44 of 54 checks passed
@github-project-automationgithub-project-automationbot moved this fromIn Progress toDone inSprint 2024May 19, 2025
@tomasr8tomasr8 deleted the jit-isinstance branchMay 19, 2025 17:34
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@brandtbucherbrandtbucherbrandtbucher approved these changes

@Fidget-SpinnerFidget-SpinnerAwaiting requested review from Fidget-SpinnerFidget-Spinner is a code owner

@markshannonmarkshannonAwaiting requested review from markshannon

Assignees

@brandtbucherbrandtbucher

Labels
Projects
Status: Done
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

3 participants
@tomasr8@Fidget-Spinner@brandtbucher

[8]ページ先頭

©2009-2025 Movatter.jp