Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.7 dataclass: Raise error when assigning a value to undefined attribute

I want to limit the usage of a dataclass to the users of my code and am wondering how can I raise an error in the following context:

from dataclasses import dataclass

@dataclass
class Foo:
    attr1: str

foo = Foo("1")
foo.attr2 = "3" #I want this line to raise an exception

Currently the last line succeeds and do not change the underlying object. I want the last line to throw an error.

like image 515
Ju Bonn Avatar asked Mar 07 '26 01:03

Ju Bonn


1 Answers

You can add a __slots__ attribute to a dataclass like any other class. Attempting to create new attributes of an instance will then fail with AttributeError:

@dataclass
class Foo:
    __slots__ = ("attr1",)
    attr1: str

foo = Foo("1")
foo.attr2 = "3"
# AttributeError: 'Foo' object has no attribute 'attr2'
like image 190
Patrick Haugh Avatar answered Mar 09 '26 19:03

Patrick Haugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!