Patch method in a package that is shadowed in __init__.py

Question:

I have a folder structure like this:

├─ some_module/
│  ├─ __init__.py
│  ├─ module.py
├─ main.py

With the sub-module being shadowed by its content:

# __init__.py
from .module import module

__all__ = ["module"]
# module.py
def module_b():
   print("In module_b")
    
def module():
    print("In module")
    module_b()
# main.py
from some_module.module import module
module()

The output of main.py:

In module
In module_b

I want to patch the method module_b() from main.py with the method lambda: print("other module") (leaving the content of some_module folder as it is). Expected output after running main.py:

In module
other module

How can this be done?

Asked By: Ilya

||

Answers:

It is like this:

# main.py
import sys
from some_module.module import module
sys.modules["some_module.module"].module_b = lambda: print("other module")
module()
Answered By: wim
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.