This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author simple_coder878
Recipients simple_coder878
Date 2021-10-04.20:17:33
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1633378653.41.0.620481624294.issue45366@roundup.psfhosted.org>
In-reply-to
Content
Simple example
from dataclasses import dataclass, field

@dataclass(init=False)
class TestObject(object):
    m: str = field(default='hi')
    k: list = field(default_factory=list)

    def test(self):
        print(f'm is {self.m} ')
        print(f'k is {self.k}')

if __name__ == '__main__':
    myobject = TestObject()
    myobject.test()


Produces:

Traceback (most recent call last):
  File "H:\unit_test\tests_dataclass.py", line 81, in <module>
    myobject.test()
  File "H:\unit_test\tests_dataclass.py", line 76, in test
    print(f'k is {self.k}')
AttributeError: 'TestObject' object has no attribute 'k'
m is hi 

So m is initialized to hi but k just disappears

But wait there's more!

If i do 

from dataclasses import dataclass, field

@dataclass(init=False)
class TestObject(object):
    m: str = field(default='hi')
    k: list = field(default_factory=list)

    def test(self):
        print(f'm is {self.m} ')
        print(f'k is {self.k}')


@dataclass
class InheritedTestObject(TestObject):

    def __post_init__(self):
        super().__init__()
        print(f'Inherited m is {self.m} ')
        print(f'Inherited k is {self.k}')
        print(f'Inherited g is {self.k}')


if __name__ == '__main__':
    myobject = InheritedTestObject()
    myobject.test()

It produces:

Inherited m is hi 
Inherited k is []
Inherited g is []
m is hi 
k is []

Process finished with exit code 0

NO ERRORS!

It seems like a bug to me, but what is the expected behavior in this case? I would expect the first case to not error out and should have an empty list.

I've only tested this on Python 3.9 so far.
History
Date User Action Args
2021-10-04 20:17:33simple_coder878setrecipients: + simple_coder878
2021-10-04 20:17:33simple_coder878setmessageid: <1633378653.41.0.620481624294.issue45366@roundup.psfhosted.org>
2021-10-04 20:17:33simple_coder878linkissue45366 messages
2021-10-04 20:17:33simple_coder878create