Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imported a Python module; why does a reassigning a member in it also affect an import elsewhere?

Tags:

python

import

I am seeing Python behavior that I don't understand. Consider this layout:

project
|   main.py
|   test1.py
|   test2.py
|   config.py

main.py:

import config as conf
import test1
import test2

print(conf.test_var)
test1.test1()
print(conf.test_var)
test2.test2()

test1.py:

import config as conf

def test1():
    conf.test_var = 'test1'

test2.py:

import config as conf

def test2():
    print(conf.test_var)

config.py:

test_var = 'initial_value'

so, python main.py produce:

initial_value
test1
test1

I am confused by the last line. I thought that it would print initial_value again because I'm importing config.py in test2.py again, and I thought that changes that I've made in the previous step would be overwritten. Am I misunderstanding something?

like image 229
Alexey Avatar asked Aug 25 '16 11:08

Alexey


People also ask

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.

When importing a module into a Python program What is the difference between using the import statement and using the From statement?

The import statement allows you to import all the functions from a module into your code. Often, though, you'll only want to import a few functions, or just one. If this is the case, you can use the from statement. This lets you import only the exact functions you are going to be using in your code.

What happens if you import a module twice?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.

How do you check if a module is already imported in Python?

Use: if "sys" not in dir(): print("sys not imported!")


2 Answers

test2.py

import config as conf

def test2():
    print(id(conf.test_var))
    print(conf.test_var)

test1.py

import config as conf

def test1():
    conf.test_var = 'test1'
    print(id(conf.test_var))

Change code like this.

And run main.py

initial_value
140007892404912
test1
140007892404912
test1

So, you can see that in both cases you are changing value of the same variable. See these id's are same.

like image 37
Rahul K P Avatar answered Oct 16 '22 22:10

Rahul K P


Python caches imported modules. The second import call doesn't reload the file.

like image 193
Sergey Gornostaev Avatar answered Oct 17 '22 00:10

Sergey Gornostaev