This code works as expected:
from dataclasses import dataclass
@dataclass(slots=False, init=False)
class Test:
field: str = "default value"
print(Test()) # outputs "Test(field='default value')"
However, if I change slots to True, it throws an AttributeError:
AttributeError: 'Test' object has no attribute 'field'
To fix the issue, I have to either use the generated __init__ method or initialize all the fields within a custom __init__ method explicitly. What is the reasoning behind this behavior?
You're not initializing the object with its default values anyway - your
__init__isn't initializing the object at all. However, without__slots__, it kind of looks like the default value is there, because instance attribute lookup falls back to the class, and finds thatfieldon the class is set to"default value".With
slots=True,fieldon the class isn't set to"default value"any more. It's set to a slot descriptor, responsible for retrieving slot values from the right part of the instance's memory layout. Instance attribute lookup finds the slot descriptor, which checks the slot in the instance's memory layout, and finds the slot is empty, so it raises anAttributeError.