Currently, the following code will raise an AttributeError because the class has no attribute __annotations__:
@validataclass
class ExampleClass:
pass
You can replace the decorator with the usual @dataclass validator if you need an empty dataclass, but it would be more intuitive if the @validataclass decorator worked here too. So, simply check if __annotations__ exists and silently return if it doesn't.
... BUT there is a catch to this solution: It could hide potential errors and make debugging difficult.
@validataclass
class ExampleClass:
some_field = IntegerValidator()
In this example, it's most likely an error that the field is missing the type annotation (some_field: int = IntegerValidator()). This would mean that the field doesn't even exist as a dataclass field at all. Currently, the AttributeError would be raised, so the error would be noticed.
So, better solution: Raise an error if __annotations__ is empty, but with a more userfriendly error message, and implement a parameter allow_empty that can be set to explicitly allow an empty dataclass (e.g. @validataclass(allow_empty=True).
Better solution: Detect fields with missing annotations directly, and raise errors about that. But only if the value of a field is of type Validator, Default or a tuple containing one of those (so that you can still define class variables without type annotations that are not supposed to be validated fields).
Currently, the following code will raise an AttributeError because the class has no attribute
__annotations__
:You can replace the decorator with the usual
@dataclass
validator if you need an empty dataclass, but it would be more intuitive if the@validataclass
decorator worked here too. So, simply check if__annotations__
exists and silently return if it doesn't.... BUT there is a catch to this solution: It could hide potential errors and make debugging difficult.
In this example, it's most likely an error that the field is missing the type annotation (
some_field: int = IntegerValidator()
). This would mean that the field doesn't even exist as a dataclass field at all. Currently, the AttributeError would be raised, so the error would be noticed.So, better solution: Raise an error if__annotations__
is empty, but with a more userfriendly error message, and implement a parameterallow_empty
that can be set to explicitly allow an empty dataclass (e.g.@validataclass(allow_empty=True)
.Better solution: Detect fields with missing annotations directly, and raise errors about that. But only if the value of a field is of type
Validator
,Default
or a tuple containing one of those (so that you can still define class variables without type annotations that are not supposed to be validated fields).