Sharanbr
Sharanbr

Reputation: 355

code execution upon import in Python

When I import a module in my python file, I expect execution of the imported code to be executed when I execute the file that is importing the module.

Here is the code:

I have few simple lines in test_2.py file:

x = 10
y = 20

c = x-y

print c

def func1():
    return x+y 

This is imported in another file test_2_test.py:

import test_2
x = test_2.func1()
print x

Here is the output when I execute test_2_test:

%run "D:/Projects/Initiatives/machine learning/programs/test_2_test.py" 30

I cannot figure out why "print c" statement is not executed

Upvotes: 2

Views: 5254

Answers (2)

abarnert
abarnert

Reputation: 365587

The code in test_2.py will only be executed the first time you import test_2 during an interpreter session.

You're trying to %run this from inside IPython. You've presumably imported test_2 at least once before since starting IPython. Therefore, there's nothing to run.

If you exit Python and, from bash/cmd, type python test_2_test.py, you will see the 10 and 30 both get printed.

Or, if you start up a brand new IPython session and %run test_2_test.py, same thing: it'll print both values. But only the first time; if you %run it again, from the same session, you'll only see 30.


Anyway, if you want to trick Python into re-running your module, you can do so like this:

import sys
del sys.modules['test_2']
import test_2

This is generally a bad idea, but for the specific case of testing top-level code in a module that you're not doing anything else with… well, that case is half the reason this is publicly documented:

This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.


For a slightly cleaner solution, you can tell Python to reload the module instead of importing it:

reload(test2)

… but this doesn't do much good in your case, because you want to run test_2_test and have it do the import, you don't want to do it yourself.


For more details, you can read the details of how importing works, starting with imp. But frankly, I wouldn't bother learning how pre-3.4 import works; just wait until you're ready to upgrade. The new version is much cleaner, better documented, and won't be completely obsolete knowledge in a year and a half.

Upvotes: 10

Sharanbr
Sharanbr

Reputation: 355

I think I found out the issue. I was executing the code under Canopy GUI and indeed does not execute the imported for some reason. I opened command prompt under Canopy and I get the expected results.

I will probably report this to Enthought people

Upvotes: 0

Related Questions