vendredi 24 juillet 2020

dynamically alter function args within class method

I am looking for some kind of design pattern, pattern in general, or preferably a pythonic way to handle the following issue. Suppose we have a SuperCalculator class that performs some very complex calculations and then validates it with some metrics that defaultvalidator handles by default.

class SuperCalculator:

    validator = defaultvalidator

    def do_complex_calculation(self):
        # here we do some static but complex calculations

        # arg1 and arg2 are baked into `do_complex_calculation`'s
        # call of `self.validator`
        if self.validator(arg1, arg2):
            return calculation 
        else:
            raise SuperCalculatorExc()

Now assume the client wants to dynamically change the validator to use completely different metrics, including different args passed into the validation process. Or even if the client wanted to extend SuperCalculator, how can they make similar changes without making them override do_complex_calculations?

sc = SuperCalculator()
sc.validator = customvalidator
sc.do_complex_calculation()

The issue here is that do_complex_calculation has arg1, arg2 baked into its call of self.validator. Is there a design pattern that will help solve this issue? I've had trouble researching this and would appreciate any feedback. Thank you.

Aucun commentaire:

Enregistrer un commentaire