Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot change behavior of imported function. #2

Closed
zhengjxu opened this issue Feb 12, 2020 · 1 comment
Closed

Cannot change behavior of imported function. #2

zhengjxu opened this issue Feb 12, 2020 · 1 comment

Comments

@zhengjxu
Copy link

If the function has already been loaded in another module at the beginning, then after we do the monkey patch in the original module, that already loaded function's behavior in another module is still not changed.

Eg. mod1.py has func_a, func_a is imported in mod2.py. We monkey patch func_a in mod1.py, but before we do the modification, func_a is already imported into mod2.py for some reason. In this case, the func_a in mod2.py is not updated.

@christophercrouzet
Copy link
Owner

christophercrouzet commented Feb 12, 2020

Yes @zhengjxu, you're correct when saying that this doesn't wortk.

Unfortunately there is nothing that I can do to change this behaviour as this is simply how Python is designed.

When you first execute mod2.py, Python also executes all the modules to import, such as mod1.py, and compiles the result into a file containing all the byte code necessary to use mod2.py. Then, when you import mod1.py from another module to patch it, it will create yet another compiled file for that other module but won't change the modules already compiled, like the one for mod2.py.

In other words, you have to do all the monkey patching operations before you import any of these modules.

I hope this helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants