Skip to content

[1.16 regression] narrowing on is_dataclass #19139

Closed
@henryiii

Description

@henryiii

Bug Report

If you use isinstance(item, type), this used to be used in conjunction with dataclasses.is_dataclass to identify types and instances. It's the recommendation in the CPython documentation, in fact: https://docs.python.org/3/library/dataclasses.html#dataclasses.is_dataclass. However, the latests MyPy no longer narrows this correctly (from what I can tell, unless I'm doing something wrong), and still thinks I might have an instance, which then breaks later when creating an instance, etc.

Note that I can flip the order, in which case I just get builtins.type for both versions. This isn't enough to fix it for some of the more complex usages in scikit-build-core, though.

To Reproduce

import dataclasses

raw_target: object

if isinstance(raw_target, type) and dataclasses.is_dataclass(raw_target):
    reveal_type(raw_target)

Expected Behavior

This is from 1.15:

tmp.py:6: note: Revealed type is "Type[_typeshed.DataclassInstance]"

Actual Behavior

tmp.py:6: note: Revealed type is "Union[_typeshed.DataclassInstance, Type[_typeshed.DataclassInstance]]"

Your Environment

  • Mypy version used: uvx --from git+https://github.com/python/mypy mypy tmp.py was used, so latest commit, also latest release 1.15 version for comparison.
  • Python version used: 3.13

Noticed in hauntsaninja/mypy_primer#174.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-typeguard-typeisTypeGuard / TypeIs / PEP 647 / PEP 742

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions