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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With