Reputation: 1741
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')
- 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 ofanother_module
,one accessible forfoo.py
and one formain.py
?- Is there a way to not
import another_module
if it has already been done in themain
?- How does it works if in the main i have
from another_module import f1
, and in foo.pyfrom another_module import f1,f2
.Is f2 just "added" or module reloaded?
Upvotes: 0
Views: 250
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