Skip to content

ClassVar breaks dataclass fields #125994

@michael-123123

Description

@michael-123123

Bug report

Bug description:

Hi,

I searched issues and couldn't find anything similar to this.
I'm not 100% sure it's a bug - possibly this is desired behavior?

To reproduce:

from dataclasses import Field, field, dataclass
from typing import ClassVar


class A:
    sentinel: ClassVar[Field] = field()


@dataclass
class B:
    sentinel: ClassVar[Field] = field()


print("Class A")
print(A.sentinel)
print(A().sentinel)
print()


print("Class B")
try:
    print(B.sentinel)
except AttributeError as ex:
    print(ex)

try:
    print(B().sentinel)
except AttributeError as ex:
    print(ex)

print()

Output:

Class A
Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object at 0x78ec801c1010>,default_factory=<dataclasses._MISSING_TYPE object at 0x78ec801c1010>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object at 0x78ec801c1010>,_field_type=None)
Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object at 0x78ec801c1010>,default_factory=<dataclasses._MISSING_TYPE object at 0x78ec801c1010>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object at 0x78ec801c1010>,_field_type=None)

Class B
type object 'B' has no attribute 'sentinel'
'B' object has no attribute 'sentinel'

Upon inspection of B.__dataclass_fields__ the sentinel field does appear in B.
Which is somewhat confusing behavior.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions