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?
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()
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?
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()