Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
In other module

How can this be done?

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading