Python – Import from Parent Directory

Python – Import from Parent Directory

In Python application development, creating a directory setup with various subdirectories each housing its respective modules and packages is a standard practice. This setup promotes code reusability through the importation of external code, consequently accelerating the development cycle by saving time and resources.

The Python – Import from Parent Directory facilitates the integration of modules from a parent directory, which is situated a level higher in the directory hierarchy. This procedure is particularly beneficial when there is a necessity to utilize a module or package in numerous projects distributed across different directories within a unified parent directory.

Nonetheless, Python intrinsically recognizes only the modules present in the existing directory and those identified in the PYTHONPATH environment variable, posing challenges in importing modules from the parent directory. This piece delves into various strategies to overcome this hindrance in Python, illustrating the functioning of these techniques through pertinent examples.

Directory Structure

Python – Import from Parent Directory

The screenshot above was captured in Visual Studio. It showcases a parent directory dubbed “parent_dir,” within which resides a Python file titled “tests.py.” A subsidiary directory labeled “sub_dir” is also present, holding a Python document named “sub_dir_file.py.” The task at hand is to facilitate the importation of the “tests” module found in the “parent_dir” directory, utilizing the “sub_dir_file.py” script situated in the “sub_dir” directory.

Module in Parent Directory – tests.py

def test_method():
    print("Hi ! You are in test module :)")

Python file in Sub-Directory – sub_dir_file.py

from parent_dir import tests
​
# from tests module
tests.test_method()

Output

Python – Import from Parent Directory

Executing the aforementioned code in the sub_dir_file.py file will result in an error. The following techniques can be employed in Python to facilitate importing from a parent directory.

Using sys.path.append() Method

A method to facilitate the importation of code from a parent directory entails the alteration of the system path through the manipulation of the sys.path list. This list delineates the directories Python refers to during the importation of modules. Adding the parent directory’s path to sys.path enables the importation of packages or modules situated in the parent directory. Below is a demonstration:

import sys
​
sys.path.append('../parent_dir')
​
from tests import test_method
​
test_method()

Output

output

In the given illustration, we add the pathway to the parent directory (../parent_dir) to sys.path. Following this, we import the tests module found in the parent directory and employ the test_method function.

Using os.path.dirname() Method:

To import tests module from test.py in the parent directory, you can use the following code:

mport os
import sys
​
# Get the path to the parent directory
parent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
​
# Add the parent directory to the system path
sys.path.append('../parent_dir')
​
# Import the module from the parent directory
from tests import test_method
​
# Call the method
test_method()

Output

In this script, we initially employ os.path.realpath(file) to acquire the full path to the existing file (sub_dir_file.py). Following this, we apply os.path.dirname() two times to obtain the parent directory’s path.

This derived path is then housed in a variable termed parent_dir. Subsequently, we use the sys.path.append() function to include the parent directory (../parent_dir) in the Python system path. This system path comprises a series of directories that Python scans when it is in search of modules to import.

Having included the parent directory in the system path, we are now equipped to utilize the statement ‘from tests import test_method’ to import the test_method function from the tests module situated in the parent directory.

Subsequently, we invoke the test_method() function to run the code contained in that function.

On the whole, leveraging os.path.dirname() to import from a parent directory presents a straightforward and uncomplicated approach to importing modules from disparate directories without the necessity to alter the PYTHONPATH environment variable or resort to external libraries. However, it mandates manual traversal through the directory hierarchy utilizing os.path.dirname() on several occasions to access the parent directory, a process that might turn tedious in the event of a convoluted directory structure.

Using os.path.abspath() Method

To import a module from a parent directory using the os.path.abspath() method, you can use the following code:

import os
import sys
​
# Get the path to the parent directory
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
​
# Add the parent directory to the system path
sys.path.append(parent_dir)
​
# Import the module from the parent directory
from tests import test_method
​
# Call the method
test_method()

Output

Using os.path.abspath() Method

The code outlined above illustrates the procedure for importing modules from a parent directory utilizing the os and sys Python modules. Initially, we determine the complete path to the parent directory, achieved through the application of os.path.abspath() and os.path.join() functions.

In this process, os.path.join() is employed to merge the current file directory (ascertained through os.path.dirname(file)) and the parent directory (denoted as “..”), consequently producing a unified path. This path is forwarded to os.path.abspath(), responsible for returning the absolute path corresponding to the parent directory.

Upon securing the path to the parent directory, the ensuing phase involves its addition to the system path via sys.path.append(). This modification enables Python to explore the parent directory during the execution of an import statement.

Subsequently, the ‘from tests import test_method’ directive is applied to import the module from the parent directory, specifying ‘tests’ as the module’s label and ‘test_method’ as the function intended for importation. The acquired function is then activated through a test_method() call.

Note:

Be aware that the precise module and function denominations in this instance are subject to alteration based on the project’s structural and nominal norms.

Conclusion

Wrapping up, this discussion has furnished strategies and illustrative cases for performing Python imports from a parent directory, a task potentially intricate given Python’s inherent tendency to restrict module searches to the current directory and those enlisted in the PYTHONPATH environment variable. Nonetheless, we discerned that the sys.path.append(), os.path.dirname(), and os.path.abspath() techniques empower developers to fetch modules from a parent directory, thereby facilitating the recycling of pre-existing code to enhance the productivity of their Python projects.

Read More:
1: Python was not found; run without arguments

2: Python Parallel For Loop

3: Error: Legacy-Install-Failure

Coding Spell | Python Journey

Latest posts by Muhammad Usman Shafique (see all)