[issue46134] Confusing error message for AttributeError with dataclasses

Alex Waygood report at bugs.python.org
Sun Dec 19 14:07:33 EST 2021


Alex Waygood <Alex.Waygood at Gmail.com> added the comment:

Thanks for the bug report, Landon! I think I can reproduce this with a slightly shorter code snippet, but I don't think this is a bug:

```
>>> from dataclasses import dataclass, field
>>> @dataclass
... class Character:
...     sort_index: int = field(init=False, repr=False)
...     intelligence: int
...     def __post_init__(self):
...         self.sortindex = self.intelligence
... 
>>> c = Character(intelligence=50)
>>> c
Character(intelligence=50)
>>> c.sortindex
50
>>> c.sort_index
AttributeError: 'Character' object has no attribute 'sort_index'. Did you mean: 'sortindex'?
```

This seems like the correct error message to me.

The issue is that your "Character" class has a field named "sort_index", but that field is never assigned to. Instead, you assign an attribute named "sortindex" in your __post_init__ method. So the error message is correct: an instance of your Character class has no attribute "sort_index" (it only has a field named "sort_index"), but it *does* have an attribute "sortindex".

----------
nosy: +AlexWaygood, eric.smith
status: open -> pending
title: Dataclass Suggestion reversed: sortindex / sort_index -> Confusing error message for AttributeError with dataclasses

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46134>
_______________________________________


More information about the Python-bugs-list mailing list