Override the module method where used ... import

I have a problem to override the method from which the ... import statement is used. An example to illustrate the problem:

# a.py module def print_message(msg): print(msg) # b.py module from a import print_message def execute(): print_message("Hello") # c.py module which will be executed import b b.execute() 

I would like to override the print_message (msg) method without changing the code in module a or b. I tried in many ways, but from ... import imports the original method. When I changed the code to

 import a a.print_message 

than I see my change.

Could you suggest me how to solve this problem?
Thanks in advance for any small example.

Regards

------------------ Update ------------------
I tried to do this, for example below:

 # c.py module import b import a import sys def new_print_message(msg): print("New content") module = sys.modules["a"] module.print_message = new_print_message sys.module["a"] = module 

But this does not work when I use for ... import statement. I work only for import, but as I wrote, I do not want to change the code in the b.py and a.py modules.

+19
python
May 31 '12 at 7:30 a.m.
source share
1 answer

If your modules a and b not touched, you can try to implement c as follows:

 import a def _new_print_message(message): print "NEW:", message a.print_message = _new_print_message import b b.execute() 

You must first import a , then override the function, and then import b so that it uses the module a , which has already been imported (and modified).

+34
May 31 '12 at 7:44
source share



All Articles