Nikita Sobolev <m...@sobolevn.me> added the comment:

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.

----------
nosy: +sobolevn

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue45366>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to