eagertoLearn
eagertoLearn

Reputation: 10142

Why does importing a module executes all statements in python?

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

# this is the output of the execution
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 have not used the instruction import test1 which cause everything to be executed.

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

  2. How to just import the regions list from test1 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.

Upvotes: 6

Views: 3314

Answers (3)

Dietrich Epp
Dietrich Epp

Reputation: 213368

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.

Upvotes: 6

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9704

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.

Upvotes: 1

Sam Hartman
Sam Hartman

Reputation: 6499

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.

Upvotes: 5

Related Questions