Skip to content

Default value to dataclass field is ignored if setting up getter/setter #94067

@subercui

Description

@subercui

Bug report

As the title describes, for example, if I run the following,

from dataclasses import dataclass, InitVar


@dataclass
class Test:
    b: int = 6
    id: InitVar[int]=1

    def __post_init__(self, id=0):
        print(f"the value of id is {id} in the post_init")
        print(f"is id a property: {isinstance(id, property)}")
        self._id = id

    @property
    def id(self):
        print("using the getter")
        return self._id

    @id.setter
    def id(self, to):
        print("using the setter")
        self._id = to


print("\nInit with position argument")
a = Test(1)
print("a is", a)
print("a.id is", a.id)

print("\nInit with explicit key")
a4 = Test(id=4)
print("a4.id is", a4.id)

In the position argument initialization case, I expect to have a.id been initialized as either 1 or 0 (I think either behavior is acceptable). However, turns out the value is never set. The actual print-out is as follows:

Init with position argument
the value of id is <property object at 0x7f03526be450> in the post_init
is id a property: True
a is Test(b=1)
using the getter
a.id is <property object at 0x7f03526be450>

Init with explicit key
the value of id is 4 in the post_init
is id a property: False
using the getter
a4.id is 4

I've also tested setting id as an actual field(init=True/False), and the same issue occurs.

Your environment

  • CPython versions tested on: 3.9.5
  • Operating system and architecture: Ubuntu 18.04.6 LTS, x86_64

Metadata

Metadata

Assignees

Labels

stdlibPython modules in the Lib dir

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions