rewriting method with less arguments - Python

Viewed 50

For simplicity, I have an old class cal1 with a method def calculate(self,a,b,c,d,e) and there are many places that call this method, ex: ans=cal1.calculate(a,b,c,d,e).

Now I have a new class cal2 that supposed to substitute the the old class with all methods reusing same names ascal1 , but new one needs only fewer arguments c,d,e def calculate(self,c,d,e) and not a,b.

Question: Is there a way to retrofit the new method calculate(self,c,d,e) to old codes without changing every single lines in the old code (ex: keeping ans=cal.calculate(self,a,b,c,d,e) )? The only way I know is to change new method to take a and b as dummy, calculate(dummy_a, dummy_b, c, d, e), but then for future code I'll need to carry dummy_a, dummy_b.

1 Answers

IF you specify the arguments via keywords (for example c="value", d="value", e="value", then it's nice an clean.

With positional arguments you can capture and unpack only the items you want.

Old calculate function signature

def calculate(self, a, b, c, d, e):
    ...

new calculate method signature (with keyword arguments):

You can use the **kwargs to capture all unnecessary arguments here.

def calculate(self, c, d, e, **kwargs):
    ...

new calculate method signature (with positional arguments):

You can use the *args to capture all arguments and pull out the ones you want.

def calculate(self, *args):
    *unnecessary, c, d, e = args
    ...
Related