Pierpaolo
Pierpaolo

Reputation: 1741

import behaviour with already loaded modules

Given this situation:

Foo.py:

import another_module

def foo():
#some code

It is called by different modules, some of them already import another_module,some other don't.(let's call one of them 'main.py')

  1. Which is the default behaviour? Is the module re-loaded?If yes,(that's just a curiosity) let's suppose that another_module has changed between the import in the main and the import in foo.py. Python does have in memory two different version of another_module,one accessible for foo.py and one for main.py?
  2. Is there a way to not import another_module if it has already been done in the main?
  3. How does it works if in the main i have from another_module import f1, and in foo.py from another_module import f1,f2.Is f2 just "added" or module reloaded?

Upvotes: 0

Views: 250

Answers (1)

BartoszKP
BartoszKP

Reputation: 35911

No, modules are not reloaded. You can use the reload() function to reload a module. After importing a module it is being added to the sys.modules dictionary. As the documentation states, you can also force a module to be reloaded by altering contents of this variable:

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.

The from statement isn't any difference with regard to this behaviour. It just controls which parts of the loaded module are being added to the current scope:

Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The statement comes in two forms differing on whether it uses the from keyword. The first form (without from) repeats these steps for each identifier in the list. The form with from performs step (1) once, and then performs step (2) repeatedly.

You can easily verify this yourself:

y.py:

print "Y"

def f1():
    pass

def f2():
    pass

x.py:

print "X"

from y import f1, f2

test.py:

from y import f1

import x

print "reload"

reload(x)

python test.py

Y
X
reload
X

Upvotes: 2

Related Questions