python / cpython

The Python programming language
https://www.python.org
Other
63.04k stars 30.19k forks source link

DataClass typo-unsafe attribute creation & unexpected behaviour (dataclasses) #83643

Open 45c2da35-8699-4cad-a3c8-087dff6fb978 opened 4 years ago

45c2da35-8699-4cad-a3c8-087dff6fb978 commented 4 years ago
BPO 39462
Nosy @ericvsmith
Files
  • bug_demo_dataclass_typo_unsafe.py: Demo of Unsafe Attribute Assingment in DataClass + suggested solution
  • bug_demo_dataclass_typo_unsafe.py: Update: Demo of Unsafe Attribute Assingment in DataClass + suggested solution
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields: ```python assignee = None closed_at = None created_at = labels = ['3.7', '3.8', 'type-bug', 'library', '3.9'] title = 'DataClass typo-unsafe attribute creation & unexpected behaviour (dataclasses)' updated_at = user = 'https://bugs.python.org/marcelpvisser' ``` bugs.python.org fields: ```python activity = actor = 'xtreak' assignee = 'none' closed = False closed_date = None closer = None components = ['Library (Lib)'] creation = creator = 'marcelpvisser' dependencies = [] files = ['48865', '48866'] hgrepos = [] issue_num = 39462 keywords = [] message_count = 2.0 messages = ['360752', '360753'] nosy_count = 2.0 nosy_names = ['eric.smith', 'marcelpvisser'] pr_nums = [] priority = 'normal' resolution = None stage = None status = 'open' superseder = None type = 'behavior' url = 'https://bugs.python.org/issue39462' versions = ['Python 3.7', 'Python 3.8', 'Python 3.9'] ```

    45c2da35-8699-4cad-a3c8-087dff6fb978 commented 4 years ago

    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.

    45c2da35-8699-4cad-a3c8-087dff6fb978 commented 4 years ago

    The demo-script also needs:

    "from dataclasses import dataclass"

    Sorry about this omission, I've attached the update