Question

This is my module:

test1.py

regions=["a","b","c"]
print "from test1 module"

test2.py

from test1 import regions
print "from test2 module", regions

Running the test2.py

python test2.py 
from test1 module
from test2 module ['a', 'b', 'c']

I see that the print statement from test1.py is called, although I only import regions list from test1.py. I don not say import test1.py for everything to be executed.

1) why does it execute everything in test1.py file (of course not the __name__==__main__ if included).

2) How to just import the regions list from test1 module without executing all the other statements?

I did not know this is how import works and I have been working on a bug due to this for 3 days.

Was it helpful?

Solution

That is just how imports work.

def my_function():
    print("Hello")

What is the above snippet of code? It is a function definition for sure, but function definitions in Python are statements, and they must be executed in order to define the function. So when you import the above module, it executes the def, which creates a new function and assigns it to my_function. It's basically the same as:

my_function = ...definition..

So when you import a module, you always execute its contents. Otherwise you wouldn't be able to use any functions (or classes) in that module.

There are other ways to define functions in Python for sure.

def create_my_function(x):
    def local_function():
        print(x)
    global my_function
    my_function = local_function

create_my_function("Hello")

This is broadly equivalent to the original definition of my_function().

Since you can put any statements in a Python module, Python has no way of knowing which statements must be executed in order to define the symbols you are interested in. So it must execute all the statements.

OTHER TIPS

Python needs to execute all statements in a module because they may have related side effects. For example consider

a = 2
b = a*3

What happens if I import b from that module? In general, modules other than main should not have side effects that are harmful when imported. In general modules should define classes, functions and variables, but should not do things like open files, connect to databases etc.

This is the way import works - python executes the module when importing. This has it's uses as you can include functionality to validate dependencies, or initialise functionality before the importing module actually invokes any of the classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top