Python Import from Parent Directory in Simple Way

In Python, to use different functions in our code, we usually import different modules.

Importing modules saves every programmer from creating redundant code or implementing the same functions in other files.

How does Python Import from Parent Directory?

In Python, you must first set a path to the system’s absolute path before you can import from a parent directory.

Meanwhile, to import a file in Python, use the import statement.

When importing from a parent directory in Python, set the path to the system’s absolute path

Wherein we can import modules from where we are currently working.

However, we cannot import modules from the parent directory.

However, we can import the child directory by giving the name of the current module, then a dot, and then the name of the child module.

Below is the hierarchy of the files that are stored in a directory.

Import Module from Parent Directory

Let’s say we want to import a module from the parent directory of the current project directory.

3 Ways to Import from Parent Directory in Python

There are three different ways to do this, thus are explained below.

1. Import a Module from the Parent Directory in Python Using the Relative Import

Using the current directory path as a point of reference, the relative import is used to import a module into the code.

We import a module into the code using relative import by referring to the current directory path.

Then, we add the __init__.py file to the parent directory to make the directory a package.

We use the import statement to bring in a module.

After the parent directory has been configured as a package, we can use the relative package method to import the module.

Directory Tree:

parentdirectory
├── main.py
├── parent-file-sample.py
├── parent-file-sample2.py
├── __init__.py
└── childdirectory
    ├── child-file-sample.py
    ├── chile-file-sample2.py
    └── __init__.py

Let’s say, for example, that child-file-sample.py is the current directory.

The example code given below shows how to import a module from its parent package.

from ..parentdirectory import sample_module

To import the module from the directory two levels above the current one, we need to put three dots before the package directory name to go back to two levels, as shown in the code below.

from ...rootdirectory import sample_module

Should I use relative or absolute imports in Python?

The preferred way to import in Python is through absolute imports because they are clear and easy to understand.

By looking at the statement, you can tell exactly where the imported resource is.

Moreover, absolute imports are still valid even if the location of the import statement moves.

2. Import a Module From the Parent Directory in Python by Adding It to PYTHONPATH

The PYTHONPATH environment variable specifies the list of directories from which Python should import modules and packages.

Therefore, if we include the parent directory from which the module must be imported, Python will automatically search the parent directory for the appropriate module.

3. Using the sys.path.insert() Method

Another method is using sys.path.insert() to add the parent directory to the sys.path list. The sys.path is the list of strings that specifies the paths to find packages and modules.

The PYTHONPATH environment variable’s directory list is stored in the sys.path file. The sys.path.insert() method can be used to add other paths.

In Python, you can use the sys.path.insert() method to add the parent directory to the sys.path list.

The code below shows how to demonstrate this.

import os, sys

path_abs = os.path.abspath('.')
sys.path.insert(1, path_abs)

import sample_module

Summary

This Python tutorial explained the different methods of how Python import from the parent directory.

If you found the information in this article useful, please consider sharing it with others who may find it useful as well.

What method of Python import do you prefer? Let us know in the comment section below.

Related Python Tutorials

Common use cases for Python Import from Parent Directory in Simple Way

  • Data pipelines. Python is the standard for ETL, data analysis, and ML workflows.
  • Web development. Django and FastAPI power modern web backends and APIs.
  • Automation and scripting. System administration, file processing, web scraping, and cron jobs.
  • Machine learning. scikit-learn, PyTorch, TensorFlow, Hugging Face for AI/ML projects.
  • Educational tools. Python’s readability makes it the go-to teaching language.

Working code example

from typing import Optional

def process_data(items: list[dict]) -> Optional[dict]:
    """Process a list of items and return summary stats."""
    if not items:
        return None
    return {
        "count": len(items),
        "total": sum(item.get("value", 0) for item in items),
        "avg": sum(item.get("value", 0) for item in items) / len(items),
    }

# Usage
data = [{"value": 10}, {"value": 20}, {"value": 30}]
summary = process_data(data)
print(summary)  # {'count': 3, 'total': 60, 'avg': 20.0}

Best practices

  • Use type hints. list[dict], Optional[str], and TypedDict make code self-documenting and enable static analysis.
  • Follow PEP 8. Consistent style improves readability. Use black or ruff to auto-format.
  • Prefer f-strings. f”{value}” is cleaner than str.format() or % formatting.
  • Write tests with pytest. Aim for 70%+ coverage on business-critical modules.
  • Use ruff or pylint. Static analysis catches many bugs before code runs.

Common pitfalls

  • Mutable default arguments. def f(x=[]) reuses the same list across calls. Use x=None then check.
  • Integer division. 5/2 gives 2.5 in Python 3. Use // for floor division.
  • Missing self on methods. Class methods need self as first parameter.
  • Late binding closures. Loops that create lambdas can capture variables late.

Frequently Asked Questions

What Python version does this tutorial target?
This tutorial targets Python 3.10 or higher. Most examples work on 3.8+, but newer features (match statements, pipe union types, structural pattern matching) need 3.10+. For deep learning content, Python 3.11 is recommended for best performance.
How do I install Python for this tutorial?
Download Python 3.11 or higher from python.org. On Windows, tick ‘Add to PATH’ during install. On Mac use Homebrew (brew install python). On Linux use your package manager or pyenv for version management.
Do I need pip and virtual environments?
Yes. pip comes with Python. For any project beyond a single script, create a virtual environment: python -m venv venv, then activate and pip install dependencies. This keeps project libraries isolated.
Can I use this in a Jupyter notebook or Google Colab?
Most examples run in both. Colab is great for ML tutorials since it provides free GPU access. Jupyter is better for local iterative development. Just paste the code into a cell and run.
Where can I find more Python practice projects?
Browse itsourcecode.com Python Projects for 250+ free capstone-ready systems (sentiment analysis, image classification, chatbots, LangChain apps). Each includes full source code, dataset links, and installation instructions.

Elijah Galero


Programmer & Technical Writer at PIES IT Solution

Elijah Galero is a programmer and writer at PIES IT Solution, author of 175+ tutorials at itsourcecode.com. Specializes in Python error debugging (AttributeError, TypeError, ModuleNotFoundError), Python programming tutorials, and Microsoft Excel how-to guides for BSIT students and productivity learners.

Expertise: Python · Python Errors · Python AttributeError · Python TypeError · ModuleNotFoundError · MS Excel · MS PowerPoint
 · View all posts by Elijah Galero →

Leave a Comment