Search code examples
python-3.xpython-importmonkeypatching

Replace package import in a module


I use a module that imports a function as a package import using relative import dot notation:

from .utils import target_func

class ClassINeed:

    def function_i_call(self):
        return target_func()

I want to import ClassINeed with from classineed import ClassINeed but replace target_func with a function of my own. Problem is, target_func is not part of the class I am importing. Therefore I do not see a way to access it. What would be a way to accomplish this?


Solution

  • On top of from classineed import ClassINeed, also do a import classineed then override the target_func as needed via classineed.target_func = lambda : 'hello!' for example.

    P.S. Referring to the class ClassINeed with classineed.ClassINeed might be cleaner if you already have import classineed.