Python import modules from a higher level package

Posted on

Question :

Python import modules from a higher level package

This is my package hierarchy

|    //Empty file
   |    //Empty file
   |  |    //Empty file
   |  |
   |  |
      |    //Empty file

Now I want to import inside
So I gave
import inside

But I get the following error:

    import app.global_vars
ImportError: No module named app.global_vars

I should also mention that I am importing from is the file I am actually running. When imports, tries to import and I get the above mentioned error

What am I doing wrong here?

Asked By: Hashken


Answer #1:

If you are running app/ as a script, the parent directory of app is not added to sys.path(). The app directory itself is added instead (not as a package but as a import search path).

You have 4 options:

  1. Move out of the app package (next to it)
  2. Add a new script file next to app that only runs:

    from app import server
  3. Use the -m switch option to run a module as the main entry point:

    python -m app.server
  4. Add the parent directory of to sys.path:

    import os.path
    import sys
    parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.insert(0, parent)

    This last option can introduce more problems however; now both the app package and the modules contained in the app package are on sys.path. You can import both app.server and server and Python will see these as two separate modules, each with their own entry in sys.modules, with separate copies of their globals.

Answered By: Martijn Pieters

Answer #2:

need file, will regard it as a package


|– can be empty

Answered By: fainle

Leave a Reply

Your email address will not be published. Required fields are marked *