Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submodule importing primary module

First of all, my apologies if this question has already be asked elsewhere. I really searched for it, but didn't find anything.

The situation is the following: In a folder mod, I have the files __init__.py and sub.py. They contain the following data: __init__.py:

print "mod"

sub.py:

import __init__
print "sub"

Now let's do the following:

>>> import mod
mod
>>> import mod.sub
mod
sub

But when doing import mod.sub, why is mod/__init__.py executed again? It had been imported already. The same strange feature exists if we just call:

>>> import mod.sub
mod
mod
sub

Can I change the behaviour by changing the import __init__? This is the line that seems most likely wrong to me.

like image 733
Turion Avatar asked Sep 21 '11 17:09

Turion


2 Answers

You can actually inspect what is going on by using the dictionary sys.modules. Python decides to reload a module depending on the keys in that dictionary.

When you run import mod, it creates one entry, mod in sys.modules.

When you run import mod.sub, after the call to import __init__, Python checks whether the key mod.__init__ is in sys.modules, but there is no such key, so it is imported again.

The bottom line is that Python decides to re-import a module by keys present in sys.modules, not because the actual module had already been imported.

like image 126
Olivier Verdier Avatar answered Nov 13 '22 04:11

Olivier Verdier


you should replace

import __init__

by

import mod
like image 1
Xavier Combelle Avatar answered Nov 13 '22 06:11

Xavier Combelle