Skip to content

Overzealous Optimization For isinstance #144873

@George-Ogden

Description

@George-Ogden

Bug report

Bug description:

The custom __instancecheck__ dunder method allows full customization (described in the Data model).

However, it produces a spurious result:

class CustomIsInstanceMeta(type):
    def __instancecheck__(cls, instance: object) -> bool:
        return type(instance) is int

class CustomIsInstance(metaclass=CustomIsInstanceMeta):
    ...

class CustomIsInstanceSubclass(CustomIsInstance):
    ...


print(isinstance(5, CustomIsInstance)) # True
print(isinstance(CustomIsInstance(), CustomIsInstance)) # True (should be False)
print(isinstance(CustomIsInstanceSubclass(), CustomIsInstance)) # False

This is caused by:

cpython/Objects/abstract.c

Lines 2641 to 2644 in 23c488d

/* Quick test for an exact match */
if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
return 1;
}

which is invalid in this case.

This is a reframing of #79264 (request to fix documentation)

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions