Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

python - Override module method where from...import is used

I have a problem overriding the method where from...import statement is used. Some 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'd like to override print_message(msg) method without changing code in a or b module. I tried in many ways but from...import imports the original method. When I changed the code to

import a
a.print_message

then I see my change.

Could you suggest how to solve this problem?

------------------ Update ------------------

I tried to do that like below e.g.:

# 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 is not working where I'm using for...import statement. Is working only for import a but as I wrote I don't want change code in b.py and a.py modules.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With your a and b modules untouched you could try implementing c as follows:

import a

def _new_print_message(message):
    print "NEW:", message

a.print_message = _new_print_message

import b
b.execute()

You have to first import a, then override the function and then import b so that it would use the a module that is already imported (and changed).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...