Import Script from a Parent Directory

PythonImport

Python Problem Overview


How do I import a module(python file) that resides in the parent directory?

Both directories have a __init__.py file in them but I still cannot import a file from the parent directory?

In this folder layout, Script B is attempting to import Script A:

Folder A:
   __init__.py
   Script A:
   Folder B:
     __init__.py
     Script B(attempting to import Script A)

The following code in Script B doesn't work:

import ../scriptA.py # I get a compile error saying the "." is invalid

Python Solutions


Solution 1 - Python

You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

In general it is preferable to use absolute imports rather than relative imports.

toplevel_package/
├── __init__.py
├── moduleA.py
└── subpackage
    ├── __init__.py
    └── moduleB.py

In moduleB:

from toplevel_package import moduleA

If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.

Solution 2 - Python

From the docs:

from .. import scriptA

You can do this in packages, but not in scripts you run directly. From the link above:

> Note that both explicit and implicit relative imports are based on the > name of the current module. Since the name of the main module is > always "_main_", modules intended for use as the main module of a > Python application should always use absolute imports.

If you create a script that imports A.B.B, you won't receive the ValueError.

Solution 3 - Python

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.

Then:

import module_you_wanted

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsazrView Question on Stackoverflow
Solution 1 - PythonjfsView Answer on Stackoverflow
Solution 2 - PythonRob WoutersView Answer on Stackoverflow
Solution 3 - PythoncapfredfView Answer on Stackoverflow