-
-
Notifications
You must be signed in to change notification settings - Fork 33.1k
Description
Bug report
Bug description:
When declaring a subclass for a dataclass
, including/omitting type hints change the behavior of inherited attributes. It seems that if the parent class has a type hint but the child class does not, the child class will not override the parent's attribute value.
Example for reproducing issue
from dataclasses import dataclass
@dataclass
class Field:
name: str
d_type: str = 'CustomType'
@dataclass
class FieldStr(Field):
d_type: str = 'string'
@dataclass
class FieldStrNoHint(Field):
d_type = 'string'
my_field = FieldStr('FieldWithString')
print(my_field.d_type) # expected: 'string', actual: 'string'
my_field = FieldStrNoHint('FieldWithStrNoHint')
print(my_field.d_type) # expected: 'string', actual: 'CustomType'
Expected Behavior
In both cases (FieldStr
and FieldStrNoHint
), the d_type
attribute should return 'string'
.
Actual Behavior
The child class with a type hint (FieldStr
) correctly returns the value.
The child class without a type hint (FieldStrNoHint
) returns the parent's value instead.
In this table, the result should always be the child's value, but if the parent has a hint and the child does not, the parent's value is used instead. The hint type doesn't matter (e.g., d_type: int
on the parent still returns the same result).
Parent has hint | Child has hint | Result |
---|---|---|
Yes | Yes | Child's value |
Yes | No | Parent's value |
No | Yes | Child's value |
No | No | Child's value |
Other observations
If I change the type hint on the name
attribute in the parent class, the behavior changes more dramatically. The child class appears to set the d_type
attribute instead of the name
when instantiating the object.
@dataclass
class Field:
name = None # No hint on name
d_type: str = 'CustomType'
# ... everything else is the same
my_field = FieldStr('FieldWithString')
print(my_field.d_type) # expected: 'string', actual: 'FieldWithString'
my_field = FieldStrNoHint('FieldWithStrNoHint')
print(my_field.d_type) # expected: 'string', actual: 'FieldWithStrNoHint'
Additional Information
Main environment
- Windows 11, 24H2
- Python version: 3.12.4
Replicated environment
- Google Colab
- Python version: 3.11.11
CPython versions tested on:
3.11, 3.12
Operating systems tested on:
Windows, Other