Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override module method where from...import is used

Tags:

python

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.

like image 726
Pawel Avatar asked May 31 '12 07:05

Pawel


People also ask

What is the use of from module import?

The from.. import statement allows you to import specific functions/variables from a module instead of importing everything. In the previous example, when you imported calculation into module_test.py , both the add() and sub() functions were imported.

What are the three methods to import modules in Python?

So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.

What happens when a module is imported in Python?

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.


1 Answers

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).

like image 115
uhz Avatar answered Oct 05 '22 23:10

uhz