Home > Software engineering >  Redefine legacy function in python with calls to old
Redefine legacy function in python with calls to old

Time:04-30

Let say I have function a() which is called in many places and I am not able to trace it or change it.

I need some replacement of this function, with calls to it and also do some additional staff. The old code has many calls a() function so I need some redefinition a=b. However, example below cause infinite recursion

def a():
    return "hello" #do not edit!


def b():
    prefix = a() # get something from a
    return prefix " world"

a=b

#...somewhere
a()

Is there any possibility to do this?

CodePudding user response:

You do it with monkey-patching, by using a different variable to hold the old definition.

original_a = a

def b():
    prefix = original_a()
    return prefix   " world"

a = b

CodePudding user response:

use inheritance

class a:
    value=9
    def __init__(self):
            print("I'm a parent")
            
    def fnc():
        print("parent fnc")
    
class b(a):
    def __init__(self):
            #super().__init__()
            print("I'm a child!")
    @classmethod            
    def fnc(cls):
        super().fnc()
        print("child fnc")
    @classmethod        
    def getValue(cls):
        return super().value

output:

I'm a child!
parent fnc
child fnc
9

make a the Parent and b the SuperChild

b can now access the methods and attributes of a

your wrapping b with the functionality of a

  • Related