1

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
TFC
  • 466
  • 1
  • 5
  • 14
  • Do not use `input` as variable name. It is built in function – balderman Dec 20 '21 at 07:05
  • The obvious solution is have the caller of `action` implement the wrapping. Your example does not indicate how it is being called and whether this implementation would be problematic for other reasons. – tripleee Dec 20 '21 at 07:09
  • Check this discussion, probably this will answer you. Ref: https://stackoverflow.com/questions/19335436/decorators-on-abstract-methods – ariharan vijayarangam Dec 20 '21 at 07:11

0 Answers0