Python import module from path | Example code

How to import a Python module given the full path?

The python module is a kind of code file containing a set of functions, classes, and variables definitions. With the module, you can make code reusable and easy to understand. To use module code you have to import it.

Here are some methods to import the module by using its full path:

  • sys.path.append() Function
  • importlib Package
  • SourceFileLoader Class

Example import module from path in Python

Simple examples code: consider this is project file and modules structure:-

Python import module from path

main.py code for all example

var = "Hello main file"
num = 9876543210


def greeting(name):
    print("Hello, " + name)

Using sys.path.append() Function

The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.

import sys

# appending a path
sys.path.append('modules')

from modules import main

print(main.num)

Output: 9876543210

Using importlib Package

The importlib.util is one of the modules included in this package that can be used to import the module from the given path.

import importlib.util

spec = importlib.util.spec_from_file_location("main", "modules/main.py")

foo = importlib.util.module_from_spec(spec)

spec.loader.exec_module(foo)

print(foo.var)

Output: Hello main file

Using SourceFileLoader Class

SourceFileLoader class is an abstract base class that is used to implement source file loading with help of load_module() function which actually imports the module.

from importlib.machinery import SourceFileLoader

# imports the module from the given path
foo = SourceFileLoader("main", "modules/main.py").load_module()

foo.greeting("Kevin")

Output: Hello, Kevin

Do comment if you have any doubts and suggestions on this Python module topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.