Skip to content

attr-defined error is raised when reading default value of an InitVar field of a dataclass #19889

Open

Description

@ktns

Bug Report
I wrote a code that reads the default value of an InitVar field of a dataclass and got attr-defined error from mypy==1.18.2. But cpython==3.13.3,3.12.10 does run without error and I believe it is reasonable to assume one can read default values from InitVar fields reading the reference.

To Reproduce

import dataclasses


@dataclasses.dataclass
class Foo:
    foo: int = 42
    bar: dataclasses.InitVar[int] = 42


print(Foo.foo)
print(Foo.bar)

Expected Behavior

no-error

Actual Behavior

<string>:12: error: "type[Foo]" has no attribute "bar"  [attr-defined]

Your Environment

  • Mypy version used: 1.18.2, 1.17.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.13.3, 3.12.10

Activity

  1. added
    bug
    on Sep 19, 2025
  2. added
    topic-runtime-semantics
    on Sep 20, 2025
  3. tqa236 commented on Nov 8, 2026

    @tqa236

    Hello, there is a test that explicitly enforces the current behavior. Is this issue still a bug or it works as intended? The test is added around 4 years ago so I wonder if anything changes since.

    [case testDataclassInitVarCannotBeSet]
    from dataclasses import dataclass, InitVar
    
    @dataclass
    class C:
        x: InitVar[int] = 0
        y: InitVar[str] = ''
    
        def f(self) -> None:
            # This works at runtime, but it seems like an abuse of the InitVar
            # feature and thus we don't support it
            self.x = 1  # E: "C" has no attribute "x"
            self.y: str = 'x'  # E: "C" has no attribute "y"
    
    c = C()
    c2 = C(x=1)
    c.x  # E: "C" has no attribute "x"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugtopic-dataclassestopic-runtime-semantics

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions