Sean
Sean

Reputation: 992

accessing modules imported into __init__ without directly referencing them

If I make a test_folder.__init__ that consists of:

constant1 = 1
from test_folder import moduleVar1

and then from the parent directory, run the following script:

import sys
from test_folder import constant1
print(constant1)
print(sys.modules)

sys.modules tells me that test_folder.moduleVar1 was imported.

Output from sys.modules:

'test_folder.moduleVar1': <module 'test_folder.moduleVar1' from 'C:...\test_folder\moduleVar1.py'>

Why is this module shown as being imported when I haven't specified it to be imported?

Upvotes: 2

Views: 54

Answers (1)

Gary Wisniewski
Gary Wisniewski

Reputation: 1120

What you're seeing looks correct. You can't import just a single variable. The entire __init__ module will be imported, along with the additional import. Note that sys.modules does not indicate that something has been imported into the current namespace, and has no relation to the current namespace. Essentially, sys.modules is a global dictionary (or cache) that Python uses to be sure that if you import a module more than once, or refer to its submodules, that it does not have to reload the module, and that it will not load the same module from two different places.

So, if a module is loaded anywhere in any of the modules or libraries your code accesses, it will remain in sys.modules thereafter.

So, in your main routine, when you say:

import sys
from test_folder import constant1

It is loading your __init__ in order to access constant1, but since the __init__ code also imports moduleVar1, python will make an entry in sys.modules as a record keeping entry even though it is not imported into your main module, so you'll see the residual entry if you print out sys.modules.

Upvotes: 2

Related Questions