Summary: To import a module given the full path, the following methods can be used :
- Using the
importlib
module - Using
SourceFileLoader
class - Using
sys.path.append()
function - Adding __init__ file to the folder containing the module and then importing it
Problem: How to import a module if its full path has been given?
Example: Consider we have the following arrangement of files :
python
|--main.py
|calculator
|-----add.py
Given the above project environment, we want to import the add module from the calculator package in our main.py
class so that we get the desired result. The added module contains a function named add()
which returns the sum of two numbers. Hence, in this example, we aim to import the add module and get the sum of the two numbers.
<Code to import the add module from the calculator package>
x = int(input("first no."))
y = int(input("second no."))
r = add(x, y)
print("Sum: ", r)
Desired Output:
first no. 89
second no. 99
Sum: 188
Let us have a look at the various methods that can be used to import the add module from its given path.
Solutions:
Method 1: Using importlib Module
The importlib
module in Python serves two purposes:
- It provides an implementation of the
import
statement. - It exposes the components of the
import
statement that are responsible for the working of theimport
statement. This enables users to create their custom objects and play around with them to use the import process according to their needs.
Therefore, we can leverage the power of the importlib
module in our code to import custom packages from a given path.
Have a look at the following program which demonstrates the usage of the importlib
module to import packages (Please follow the comments to get a better grip on the given code):
import importlib.util # function to specify the module that needs to be imported relative to the package and path of the module spec = importlib.util.spec_from_file_location("add", "C:\\Users\\Shubham-PC\\PycharmProjects\\pythonProject1" "\\calculator\\add.py") # creating a new module based on spec foo = importlib.util.module_from_spec(spec) # exec_module :- An abstract method that executes the module in its own namespace when a module is imported or reloaded. spec.loader.exec_module(foo) # Program to use the imported add module x = int(input("first no.")) y = int(input("second no.")) r = foo.add(x, y) print("Sum: ", r)
Output:
first no. 89 second no. 99 Sum: 188
Disclaimer: The above method will work for Python 3.5 and above
Method 2: Using SourceFileLoader Class
If you are using Python 3.3 or above you might be fascinated to use the SourceFileLoader
class. It is an abstract base class that is used to implement source file loading.
Let us have a look at the following code to understand the usage of SourceFileLoader
class to import packages from a given path (Please follow the comments in the code for a better grip):
from importlib.machinery import SourceFileLoader # importing the add module from the calculator package using the path foo = SourceFileLoader("add", "C:\\Users\\Shubham-PC\\PycharmProjects\\pythonProject1\\calculator\\add.py").load_module() # code to use the imported add module of the calculator package x = int(input("first no.")) y = int(input("second no.")) r = foo.add(x, y) print("Sum: ", r)
Output
first no. 89 second no. 99 Sum: 188
Method 3: Using sys.path.append() Function
To import the module to your Python code, you can use the sys.path.append()
function to add the directory of the required module to the environment variable. The list of directories that Python searches for the required modules and files are stored in the path
attribute of the sys
module. Now path
is a list and we can use the append method to add new directories.
The following program demonstrates the above concept:
import sys sys.path.append("C:\\Users\\Shubham-PC\\PycharmProjects\\pythonProject1\\calculator") import add x = int(input("first no.")) y = int(input("second no.")) r= add.add(x,y) print("Sum: ",r)
Output:
first no. 89 second no. 99 Sum: 188
Method 4: Creating The Package With __init__ File
Considering that the package to be imported is within the same root folder as the class which will import a module of the package, there is another way we can import the module in our code. To import the module you must make sure that the folder containing the module has a file named __init__ added to it. This file is generally empty. Then import the module in your code as from <package_name>.<filename> import <module_name>
Let us have a look at the following code to learn how this works:
from calculator.add import add x = int(input("first no.")) y = int(input("second no.")) r = add(x, y) print("Sum: ", r)
Output:
first no. 89 second no. 99 Sum: 188
Caution: The root folder of the class importing the module and the directory that contains the module along with the __init__
file, must be the same. In other words, both of them should be within the project’s root folder.
Relative vs Absolute Imports In Python
Before we conclude this article, we must understand the subtle difference between a relative import and an absolute import in python.
Absolute Path | Relative Path |
Import using the full path. (For e.g. from projects root folder to the desired module.) | Import relative to the current location with respect to the location of the module to be imported. Relative imports use the dot notation. |
Absolute import will remain valid even when the location of the import statement changes. | Relative import will not work if the location of the import statement changes. |
Example: considering the same directory arrangement as given at the beginning of the article. from calculator import add x = int(input(“first no.”)) y = int(input(“second no.”)) r = add(x, y) print(“Sum: “, r) | Example: considering the same directory arrangement as given at the beginning of the article. from calculator import add x = int(input(“first no.”)) y = int(input(“second no.”)) r = add.add(x, y) print(“Sum: “, r) |
Conclusion
Thus from the above discussion, we can conclude that to import a module given the full path, the following methods can be used:
- Using the
importlib
module - Using
SourceFileLoader
class - Using
sys.path.append()
function - Adding
__init__
file to the folder containing the module and then importing it
Later we also discussed the key differences between relative and absolute imports.
I hope this article was helpful and you managed to gain something out of it. Please stay tuned for more interesting stuff!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.