I am writing a utility library for machine learning and want to make it as user friendly as possible. In particular, given that I implemented an abstract class with some abstract methods, is it possible to add some preprocess to the user-defined method when the abstract method is overridden? Or equivalently, automatically adding a decorator to the overridden method is also great if possible.
For example, let's say there is a base class.
class BaseModel(metaclass=abc.ABCMeta):
@abc.abstractmethod
def action(self, contents: str) -> Any:
# Do whatever user wants
raise NotImplementedError
def varify_input(self, input: Any) -> None:
# Check if input is str
if not isinstance(input, str):
raise TypeError(f"Input must be string. Got {type(input)}")
class UserDefinedModel(BaseModel):
def action(self, contents: str) -> Any:
self.varify_input(contents) # I want this line automatically added to this method.
print(contents)
As I stated in the comment, I want to implement BaseModel
class in the way that when the class is inherited and the method action
is overridden, I want to add some specific preprocess before what the child class does. In the example above, I want to add the verification of the input type and then run the user-defined process.
Perhaps I can just prepare some decorator and notify users to use the decorator when overriding the method? Yet, I want to automate it as much as possible so that users don't even need to know about the existence of such functionality.