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 sobolevn
Recipients eric.smith, simple_coder878, sobolevn
Date 2021-10-05.09:10:14
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1633425015.13.0.599859919363.issue45366@roundup.psfhosted.org>
In-reply-to
Content
Right now `dataclasses.py` has this explanation: https://github.com/python/cpython/blame/07cf10bafc8f6e1fcc82c10d97d3452325fc7c04/Lib/dataclasses.py#L962-L966

```
         if isinstance(getattr(cls, f.name, None), Field):
            if f.default is MISSING:
                # If there's no default, delete the class attribute.
                # This happens if we specify field(repr=False), for
                # example (that is, we specified a field object, but
                # no default value).  Also if we're using a default
                # factory.  The class attribute should not be set at
                # all in the post-processed class.
                delattr(cls, f.name)
            else:
                setattr(cls, f.name, f.default)
```

This is why: imagine, that we execute `.default_factory` there.
It will be vulnerable to "default mutable" problem:

```
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} ')
        self.k.append(1)
        print(f'k is {self.k}')

if __name__ == '__main__':
    myobject = TestObject()
    print(TestObject.m)  # hi
    print(TestObject.k)  # []

    myobject.test()
    # m is hi 
    # k is [1]

    other_object = TestObject()
    other_object.test()
    # m is hi 
    # k is [1, 1]
```

Another, more complex solution is to track fields with `default_factory` and still generate `__init__` / `__new__` / etc for them to run their `default_factories`s when object is created.
History
Date User Action Args
2021-10-05 09:10:15sobolevnsetrecipients: + sobolevn, eric.smith, simple_coder878
2021-10-05 09:10:15sobolevnsetmessageid: <1633425015.13.0.599859919363.issue45366@roundup.psfhosted.org>
2021-10-05 09:10:15sobolevnlinkissue45366 messages
2021-10-05 09:10:14sobolevncreate