Reputation: 1695
I'm maintaining a dictionary and that is loaded inside the config file. The dictionary is loaded from a JSON file.
In config.py
name_dict = json.load(open(dict_file))
I'm importing this config file in several other scripts(file1.py, file2.py,...,filen.py) using
import config
statement. My question is when will the config.py script be executed ? I'm sure it wont be executed for every import call that is made inside my multiple scripts. But, what exactly happens when an import statement is called.
Upvotes: 3
Views: 2054
Reputation: 365667
The top-level code in a module is executed once, the first time you import
it. After that, the module object will be found in sys.modules
, and the code will not be re-executed to re-generate it.
There are a few exceptions to this:
reload
, obviously.sys.path
, you could end up with mypackage.mymodule
and mymodule
being two copies of the same thing, in which case the code gets run twice).sys.modules
.imp
/importlib
or the like.multiprocessing
(and modules that use it indirectly, like concurrent.futures
).For Python 3.1 and later, this is all described in detail under The import system. In particular, look at the Searching section. (The multiprocessing
-specific cases are described for that module.)
For earlier versions of Python, you pretty much have to infer the behavior from a variety of different sources and either reading the code or experimenting. However, the well-documented new behavior is intended to work like the old behavior except in specifically described ways, so you can usually get away with reading the 3.x docs even for 2.x.
Note that in general, you don't want to rely on whether top-level code in the module is run once or multiple times. For example, given a top-level function definition, as long as you never compare function objects, or rebind any globals that it (meaning the definition itself, not just the body) depends on, it doesn't make any difference. However, there are some exceptions to that, and loading start-time config files is a perfect example of an exception.
Upvotes: 2