on-internet
← Community

Why slots=True makes a dataclass to ignore its default values?

Stack Overflow ·

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?

Comments

Sign in or sign up to comment and upvote.

No comments yet.