# -*- coding: utf-8 -*- """ Script that demonstrates DataClass Bug with Typo-Unsafe Attributes Also provides a solution in the form of a SafeDataClass with adjusted __setattr__ """ import dataclasses # a standard DataClass: @dataclass class DataRecordClass: attribute_1: float = 3.0 # an extended DataClass, which is typo-safe: @dataclass class SafeDataRecordClass: """Instances of this class will raise an Error if users try to set an undeclared attribute.""" attribute_1: float = 3.0 def __setattr__(self, name, value): # raise Error if field is not declared in the dataclass for field in dataclasses.fields(self): if field.name == name: super().__setattr__(name, value) return # raise error when field is not found: raise AttributeError(type(self).__name__ + ' attribute \'' + name + '\' does not exist') ########## ## Main ## ########## print('') print('-- Unsafe Data Record: -- ') print('') unsafe_record = DataRecordClass() print('print unsafe_record:', unsafe_record) # add a field to 'unsafe_record' # I would expect an Error... unsafe_record.new_attribute = 5.0 print('print unsafe_record.new_attribute:', unsafe_record.new_attribute) print('print unsafe_record:', unsafe_record) print('') print('-- Safe Data Record: --') print('') safe_record = SafeDataRecordClass() # for 'safe_record' setting an unexistent attribute does raise an Error, as expected: print('set safe record new_attribute:') safe_record.new_attribute = 5.0