python / python/mypy

`Self` not accepted when used with a `dataclass`

Open
#18,920 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-pep-695 topic-self-types topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Using Self with a dataclass raises a type-var error even though Self is an acceptable type.

Suspect it may be the same as #18812.

To Reproduce

from __future__ import annotations
from dataclasses import dataclass
from typing import Self

type HasParent[N] = N | Node[N | HasParent[N]]


class Node[P = None]:
    def parent(self) -> P: ...  # type: ignore

@dataclass
class C[P: Node | None = Node | None](Node[P]):
    item: D[Self]

class D[P: HasParent[C] = C](Node[P]):
    pass

Changing to Self to the explicit class type (item: D[C]) is accepted. Similarly using Self in a regular class (e.g. below with __init__) does not raise any errors.

class C[P: Node | None = Node | None](Node[P]):
    def __init__(self, item: D[Self]):
        self.item = item

Expected Behavior

No errors.

Actual Behavior

error: Type argument "C[P]" of "D" must be a subtype of "HasParent[C[Node[None] | None]]"  [type-var]
error: Type argument "Self" of "D" must be a subtype of "HasParent[C[Node[None] | None]]"  [type-var]

Environment

  • Mypy version used: 1.15.0
  • Python version used: 13.2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied reproduction with mypy 1.15.0, then compare the dataclass case with the regular-class variant and the explicit C type argument. Trace the existing handling of Self, dataclass fields, and generic type-variable bounds; done means the reproduction reports no errors and has a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.