Skip to content

Self not accepted when used with a dataclass #18920

Open
@jrdnh

Description

@jrdnh

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions