Import statement: Config file Python
Question: 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.


Answer: 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.
  * Accidentally importing the same module under two different names (e.g., if the module is in a package, and you've got some directory in the middle of the package in `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).
  * Installing import hooks/custom imported that replace the standard behavior.
  * Explicitly monkeying with `sys.modules`.
  * Directly calling functions out of `imp`/`importlib` or the like.
  * Certain cases with `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](http://docs.python.org/3/reference/import.html). 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.

