Let's say that I want to overload a standard function with a customized version, I can simply write
original_function_name = customized_function
For example I can do:
def custom_print(s):
print(f'!!{s}!!')
def fun1(n):
print = custom_print
print(n)
fun1(1)
>> !!1!!
However this override is only valid inside fun1. If I do
def custom_print(s):
print(f'!!{s}!!')
def fun1(n):
print = custom_print
fun2(n)
def fun2(n):
print(n)
if __name__ == '__main__':
fun1(1)
>>1
the custom print function is not passed (clearly) to fun2 which uses the standard print function. Is there a way to override the function not just in the scope where I define it, but also in all called function?
NOTE: This is a minimal example, in the real code there are several nested functions imported from different modules and I'd like to override the function in all of them without modifying them one by one.
NOTE2: I recognize this is bad practice and should not be done as it goes against a number of best-practice coding principles.