How does Python import really work? In a chain of import
Question: **Hi fellow Pythonista,**

While I have been coding with Python for quite some time now, recently I found
my some problem in my understanding of python's import mechanism.

I am hoping you guys can help me out. Thanks in advance. Your help is much
appreciated.

### Setup

    
    
    myprogram
     ┠━run.py
     ┗━mypackage                   
         ┠━ __init__.py 
         ┠━ foo.py
         ┗━ bar.py 
    

The content of the python files are as follow:

    
    
    # run.py
    import sys
    print sys.path
    from mypackage import foo
    
    # foo.py
    import sys
    print sys.path
    import bar
    
    # bar.py
    import sys
    print sys.path
    

Neither `myprogram` nor any of its sub directories is in the `PYTHONPATH`
environment variable.

### My Current Understanding

The flow of execute:

  1. Start running `run.py`. The path to the containing directory, `PATH/myprogram` is added to the `sys.path`.

  2. Executing the statement `from mypackage import foo`. Since we now have `PATH/myprogram` in the `sys.path`, the interpreter can find the `mypackage` and then locate the `foo.py` without problem. 

  3. Start running `foo.py`, the interpreter adds the path to the containing directory `PATH/myprogram/mypackage` to the `sys.path`. 

  4. At this point, both `PATH/myprogram` and `PATH/myprogram/mypackage` is included in `sys.path`.

  5. Executing the statement `import bar`. Since we have `PATH/myprogram/mypackage` added to the `sys.path`, the import statement can execute successfully without problem. 

### Question

After running the `run.py`, I discover all of the `print sys.path` statements
yield the same outputs. All of them contains `PATH/myprogram` but not
`PATH\myprogram\mypackage`, which contradicts to my understanding above.

It seems the home directory path is only added for the script that initialised
the process.But if that is the case, then how is the `import bar` statement in
`foo.py` execute successful if `PATH\myprogram\mypackage` is not in the search
path?

BTW, I am using python 2.7 on a MAC OS X machine.


Answer: sys.path is not a place to add anything by python itself.

The paths are added to modules cache, docs are clear about that:
<https://docs.python.org/release/2.7/reference/simple_stmts.html#import>

Print out the `sys.modules` and `sys.path_importer_cache` to get the overview.
The cache has the path to run.py and it can find other modules starting from
there.

