Skip to content

isinstance check against collection.abc classes fails if value has no __class__ #153772

Description

@pekkaklarck

Bug report

Bug description:

The problem can be reproduced with the following class. It succeeds when tested with isinstance() against base types like int, but fails when tested against collections.abc classes like Mapping.

>>> from collections.abc import Mapping
>>> 
>>> class NoClass:
...     def __getattribute__(self, attr):
...         if attr == "__class__":
...             raise AttributeError(attr)
...         return super().__getattribute__(attr)
...         
>>> 
>>> isinstance(NoClass(), int)
False
>>> isinstance(NoClass(), Mapping)
Traceback (most recent call last):
  File "<python-input-4>", line 1, in <module>
    isinstance(NoClass(), Mapping)
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "<frozen abc>", line 119, in __instancecheck__
  File "<python-input-0>", line 4, in __getattribute__
    raise AttributeError(attr)
AttributeError: __class__

The example class is arguably broken, but it seems objects without __class__ actually exist. For a real life example see robotframework/robotframework#5699 where the problematic object apparently is a Qt widget.

This is a very annoying case, because handling these problematic objects requires changing all isinstance usages where the type can be collections.abc class from something like

if isinstance(value, Mapping):
    ...

to

try:
    is_mapping = isinstance(value, Mapping)
except AttributeError:
    is_mapping = False
if is_mapping:
    ...

I'll do that in our code in cases where there problematic objects are likely to occur, but wrapping all isinstance usage isn't practical so I'm worried there still can be crashes.

I hope collections.abc types would be fixed so that they return False with objects without __class__ instead of failing with AttributeError. Alternatively, if objects without __class__ are considered to be totally broken, the interpreter should fail/warn when they are instantiated and not only with isinstance().

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions