Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a module and change a variable value inside module and execute it

I have a module which I need to import and change particular variable values inside imported instance of that module and then execute it.

Please note that I can not make a single change to the module being imported due to legacy reasons.

Here is what I am trying to do:

say the module i want to import, a.py, looks like

var1 = 1
var2 = 2

if __name__ == '__main__':
    print var1+var2

Now I am importing this in b.py, the caller script. I am trying to import it, change value of variable var1 and run it as main program using runpy as follows.

import runpy
import a

a.var1 = 2
result = runpy._run_module_as_main(a.__name__)

But this prints result as 3 only and not as 4 as expected.

Any other way to achieve this (apart from using runpy) without changing anything in a.py? Open to any third party module as far as I dont have to make changes in module being imported.

I am using python 2.6

like image 337
MohitC Avatar asked Oct 18 '22 06:10

MohitC


1 Answers

Here is a concrete implementation of what I proposed in the comments:

#File temp.py
var1 = 1
var2 = 2

if __name__ == '__main__':
    print var1+var2

I'm calling it via another file run.py. The key is to have another dict like class that is immune against any changes to the variables that the module might change upon importing/running it. This dictionary holds the variables whose value you want to change.

#File: run.py
class UpdatedDict(dict):
    def __setitem__(self, key, value):
        if key != "var1":
            super(UpdatedDict, self).__setitem__(key, value)

u = UpdatedDict({"var1": 10, '__name__': '__main__'})
exec open("temp.py").read() in u  #u here is the globals() for the module.

Output

~/Temp$ python run.py
12  #Yay!

Note: This is a quick and dirty implementation and is only meant to show you the way you can do it. I'd suggest going through runpy and make this code look more robust. The way it stands right now, it is a proper definition of hackish

like image 147
UltraInstinct Avatar answered Oct 21 '22 00:10

UltraInstinct