1

Imagine I import a function called main_func() from a Python package, which calls another function called_func() defined in the same file of the package.

Now, in my personal script, I want to call the main_func(). But with a small difference, when I run this main_func(), I want it to call my personally modified version of called_func(). This modified version of the function is defined in my personal script file.

How can I do this?

Example:

Script from package called package/functions.py

def main_func(a):
    return called_func(a)

def called_func(a):
    print(a)

Personal script

from package.functions import main_func

def called_func(a):
    # My personally modified function
    print(a, a)

main_func('Test ')

If I run my script, I get this output Test.

However, I would like to get Test Test

Note: I cannot modify the package files...

modesitt
  • 7,052
  • 2
  • 34
  • 64

2 Answers2

1

You can monkey patch your function into the module

import package.functions


def called_func(a):
    # your modified function
    print(a, a)


package.functions.called_func = called_func
package.functions.main_func("Test ")

Gives

Test  Test 
modesitt
  • 7,052
  • 2
  • 34
  • 64
1

Notice the import package.functions, and then the assignment of your new definition of called_func() to the one in the module.

import package.functions

from package.functions import main_func

def called_func(a):
    # My personally modified function
    print(a, a)

package.functions.called_func = called_func

main_func('Test ')
Rusty Widebottom
  • 985
  • 2
  • 5
  • 14