I have been trying to validate classes that users can create in a framework style setting. I can ensure that a class attribute is present in child classes in the following manner:
from abc import ABC, abstractmethod
class A(ABC):
@property
@classmethod
@abstractmethod
def s(self):
raise NotImplementedError
class ClassFromA(A):
pass
ClassFromA()
Which leads to the following Exception
:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class ClassFromA with abstract methods s
I can also check the type of the class attribute s
at class creation time with a decorator, like so:
from abc import ABC, abstractmethod
def validate_class_s(cls):
if not isinstance(cls.s, int):
raise ValueError("S NOT INT!!!")
return cls
class A(ABC):
@property
@classmethod
@abstractmethod
def s(self):
raise NotImplementedError
@validate_class_s
class ClassFromA(A):
s = 'a string'
Resulting in:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 3, in validate_class_s
ValueError: S NOT INT!!!
Which is useful in the eventual checking of class attributes. But this leads to verbose class definitions where each of the child classes would have to be decorated.
Is there a way to validate the class attribute (s
in the examples) in the base class? Preferably not in a too verbose way?