Correct way of "Absolute Import" in Python 2.7
Question:   * Python 2.7.10
  * In virtualenv
  * Enable `from __future__ import absolute_import` in each module

The directory tree looks like:

    
    
    Project/
        prjt/
            __init__.py
            pkg1/
                __init__.py
                module1.py
                tests/
                    __init__.py
                    test_module1.py
            pkg2/
                __init__.py
                module2.py
                tests/
                    __init__.py
                    test_module2.py
            pkg3/
                __init__.py
                module3.py
                tests/
                    __init__.py
                    test_module3.py
        data/
        log/
    

* * *

I tried to use the function `compute()` of `pkg2/module2.py` in
`pkg1/module1.py` by writing like:

    
    
    # In module1.py
    import sys
    sys.path.append('/path/to/Project/prjt')
    
    from prjt.pkg2.module2 import compute
    

But when I ran `python module1.py`, the interpreter raised an ImportError that
`No module named prjt.pkg2.module2`.

  1. What is the correct way of "absolute import"? Do I have to add the path to `Project` to `sys.path`?
  2. How could I run `test_module1.py` in the interactive interpreter? By `python prjt/pkg1/tests/test_module1.py` or `python -m prjt/pkg1/tests/test_module1.py`?


Answer: ### How python find module

_python will find module from`sys.path`, and the first entry `sys.path[0]` is
'' means, python will find module from the current working directory_

    
    
    import sys
    print sys.path
    

and python find third-party module from `site-packages`

so to absolute import, you can

**append your package to the`sys.path`**

    
    
    import sys
    sys.path.append('the_folder_of_your_package')
    
    import module_you_created
    
    module_you_created.fun()
    

**export PYTHONPATH**

the PYTHONPATH will be imported into sys.path before execution

    
    
    export PYTHONPATH=the_folder_of_your_package
    
    import sys
    [p for p in sys.path if 'the_folder_of_your_package' in p]
    

> How could I run test_module1.py in the interactive interpreter? By python
> Project/pkg1/tests/test_module1.py or python -m
> Project/pkg1/tests/test_module1.py?

you can use `if __name__ == '__main__':` idiomatic way, and use `python
Project/pkg1/tests/test_module1.py`

    
    
    if __name__ = '__main__':
        main()
    

