This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: DataClass typo-unsafe attribute creation & unexpected behaviour (dataclasses)
Type: behavior Stage:
Components: Library (Lib) Versions: Python 3.9, Python 3.8, Python 3.7
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: eric.smith, marcelpvisser
Priority: normal Keywords:

Created on 2020-01-27 11:09 by marcelpvisser, last changed 2022-04-11 14:59 by admin.

Files
File name Uploaded Description Edit
bug_demo_dataclass_typo_unsafe.py marcelpvisser, 2020-01-27 11:09 Demo of Unsafe Attribute Assingment in DataClass + suggested solution
bug_demo_dataclass_typo_unsafe.py marcelpvisser, 2020-01-27 11:18 Update: Demo of Unsafe Attribute Assingment in DataClass + suggested solution
Messages (2)
msg360752 - (view) Author: Marcel (marcelpvisser) Date: 2020-01-27 11:09
After instantiation of a variable of a DataClass, it is possible to assign new attributes (that were not defined in defining the DataClass):

data.new_attribute = 3.0  # does NOT raise Error!

This gives unexpected behaviour: if you print the variable, then 'new_attribute' is not printed (since it is not in the definition of the DataClass).

Assigning to an attribute is therefore not typo-safe (which users may expect from a DataClass).

I would expect the behaviour of the DataClass be consistent and typo-safe.

Attached is a file that demonstrates the bug (behaviour) and provides a 'SafeDataClass' by overriding the __setattr__ method.

My suggestion would be to the adjust the library __setattr__ for the DataClass such that is will be typo-safe.
msg360753 - (view) Author: Marcel (marcelpvisser) Date: 2020-01-27 11:18
The demo-script also needs:

"from dataclasses import dataclass"

Sorry about this omission, I've attached the update
History
Date User Action Args
2022-04-11 14:59:25adminsetgithub: 83643
2020-01-27 12:31:28xtreaksetnosy: + eric.smith
2020-01-27 11:18:53marcelpvissersetfiles: + bug_demo_dataclass_typo_unsafe.py

messages: + msg360753
2020-01-27 11:09:27marcelpvissercreate