Skip to content

Commit b1eb6a0

Browse files
committed
Optimize for subclasses as well
1 parent a81c02e commit b1eb6a0

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

Lib/test/test_capi/test_opt.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2020,7 +2020,7 @@ def testfunc(n):
20202020
x = 0
20212021
for _ in range(n):
20222022
# The optimization currently only narrows to bool
2023-
# the seconds argument is a tuple of classes.
2023+
# when the second argument is a tuple of classes.
20242024
y = isinstance(42, (int, str))
20252025
if y:
20262026
x += 1

Python/optimizer_bytecodes.c

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -893,16 +893,29 @@ dummy_func(void) {
893893
}
894894
JitOptSymbol *cls_sym = args[1];
895895
JitOptSymbol *inst_sym = args[0];
896+
896897
if(sym_is_const(ctx, cls_sym) && sym_matches_type(cls_sym, &PyType_Type)) {
898+
// isinstance(obj, cls) where cls is a known class
897899
PyTypeObject *cls = (PyTypeObject *)sym_get_const(ctx, cls_sym);
898-
if (sym_matches_type(inst_sym, cls)) {
899-
res = sym_new_const(ctx, Py_True);
900+
901+
if (sym_has_type(inst_sym)) {
902+
// isinstance(obj, cls) where both obj and cls have known types
903+
// We can deduce either True or False
904+
PyTypeObject *inst_type = sym_get_type(inst_sym);
905+
if (sym_matches_type(inst_sym, cls) || PyType_IsSubtype(inst_type, cls)) {
906+
res = sym_new_const(ctx, Py_True);
907+
}
908+
else {
909+
res = sym_new_const(ctx, Py_False);
910+
}
900911
}
901912
else {
913+
// isinstance(obj, cls) where obj has unknown type
902914
res = sym_new_type(ctx, &PyBool_Type);
903915
}
904916
}
905917
else {
918+
// isinstance(obj, cls) where cls has unknown type
906919
res = sym_new_type(ctx, &PyBool_Type);
907920
}
908921
}

Python/optimizer_cases.c.h

Lines changed: 8 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)