Message403206
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. |
|
Date |
User |
Action |
Args |
2021-10-05 09:10:15 | sobolevn | set | recipients:
+ sobolevn, eric.smith, simple_coder878 |
2021-10-05 09:10:15 | sobolevn | set | messageid: <1633425015.13.0.599859919363.issue45366@roundup.psfhosted.org> |
2021-10-05 09:10:15 | sobolevn | link | issue45366 messages |
2021-10-05 09:10:14 | sobolevn | create | |
|