Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 279
enkryptor Avatar asked Oct 24 '25 02:10

enkryptor


1 Answers

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 that field on the class is set to "default value".

With slots=True, field on 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 an AttributeError.

like image 69
user2357112 supports Monica Avatar answered Oct 26 '25 15:10

user2357112 supports Monica