`Self` not accepted when used with a `dataclass`
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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