Title: dataclasses slots with init=False field raises AttributeException
Type: behavior Stage:
Components: Library (Lib) Versions: Python 3.10
Status: open Resolution:
Dependencies: Superseder:
Assigned To: eric.smith Nosy List: eric.smith, tefra
Priority: normal Keywords:

Created on 2021-07-15 19:06 by tefra, last changed 2021-09-04 08:11 by tefra.

Messages (4)
msg397575 - (view) Author: Christodoulos Tsoulloftas (tefra) Date: 2021-07-15 19:06
I am trying the new slots directive but I get an AttributeError when I try to access a field with init=False

>>> from dataclasses import dataclass, field
>>> @dataclass(slots=True)
... class Example:
...     a: str
...     b: str = field(default="b", init=False)
>>> obj = Example("a")
>>> obj.__slots__
('a', 'b')
>>> obj.
obj.a  obj.b  
>>> obj.a
>>> obj.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: b. Did you mean: 'b'?

❯ python --version
Python 3.10.0b4+
msg397653 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-07-16 19:15
I created issue 44655 for the confusing error message.

The problem with dataclasses is that the instance variable 'b' needs to be initialized, instead of the current dataclasses behavior where it relies on the class variable when reading 'b'.
msg397678 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-07-17 01:51
With Pablo's changes, the error now reads (in 3.11):

AttributeError: 'Example' object has no attribute 'b'

Which is a vast improvement!

I'm working on a PR to initialize obj.b in __init__.
msg401039 - (view) Author: Christodoulos Tsoulloftas (tefra) Date: 2021-09-04 08:11
Thanks for the update eric, yeah the new error messages are much more comprehensive and I am glad to hear the original issue will be addressed as well.
Date User Action Args
2021-09-04 08:11:21tefrasetmessages: + msg401039
2021-07-17 01:51:15eric.smithsetmessages: + msg397678
2021-07-16 19:15:50eric.smithsetmessages: + msg397653
2021-07-15 19:08:47eric.smithsetassignee: eric.smith

nosy: + eric.smith
2021-07-15 19:06:03tefracreate