How to do a Python Import From Parent Directory

This tutorial will teach us how to import a Python script from a parent directory into another script. This skill is essential for organizing and reusing code in larger projects and is especially useful when working with packages and modules. We’ll cover different approaches to ensure smooth imports and tackle any potential hurdles along the way.

Prerequisites:

  • Basic understanding of Python programming
  • Familiarity with creating and running Python scripts

Setting Up the Project Structure

  1. Create a new directory for your project.
  2. Inside the project directory, create two separate Python scripts:
    • script1.py (The script that will import from the parent directory)
    • script2.py (The script that resides in the parent directory)

The Standard Approach with sys.path

  1. Open script1.py in your favorite text editor or IDE.
  2. Import the sys module at the beginning of the script: import sys.
  3. Append the parent directory path to the sys.path list:
import sys
sys.path.append("..")
  1. Now, you can import script2.py in script1.py using a standard import statement:
from script2 import some_function

Using Relative Imports

  1. Open script1.py and remove the previous import statements.
  2. To use relative imports, modify the import statement as follows:
from ..script2 import some_function
  1. Run the script from the parent directory to avoid import errors:
python -m package_name.script1

(Replace package_name with the actual name of your project directory)

The Importance of init.py

  1. Create an empty file named __init__.py in the parent directory.
  2. This file makes Python treat the directory as a package, enabling imports from it.

Using sys.path and init.py Together

  1. Open script1.py and script2.py.
  2. Remove any relative imports present and revert to standard imports.
  3. Update the sys.path modification to include the parent directory:
import sys
sys.path.append("..")
  1. In script2.py, add the following import statement at the beginning:
from . import script1

This import statement relies on the __init__.py file.

Troubleshooting and Debugging

  1. If you encounter any import errors, double-check your project structure and the presence of the __init__.py file.
  2. Verify that you are running the script from the correct location in the project directory.
  3. Ensure that there are no circular imports that might be causing conflicts.

Congratulations! You have successfully learned how to import another Python script from a parent directory. Mastering this skill allows you to organize and reuse your code more efficiently in your Python projects. Understanding both the sys.path and relative import methods allows you to choose the most appropriate approach for your specific project requirements. Happy coding!

Bonus!  If you’d like to learn more python consider taking this course!