Fundamentals 10 min read

8 Powerful Ways to Import Modules in Python (including Remote Imports)

Explore eight distinct methods for importing Python modules—from the simple 'import' statement to advanced techniques like __import__, importlib, imp, execfile, exec, the import_from_github_com package, and custom remote importers—providing practical code examples and guidance for both everyday developers and framework creators.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
8 Powerful Ways to Import Modules in Python (including Remote Imports)

The article presents eight ways to import modules in Python, ranging from the basic import statement to advanced remote importers.

1. Direct import

Commonly used method: simply import the module.

>> import os
>>> os.getcwd()
'/home/wangbm'

Other similar forms are omitted.

2. Using __import__

The __import__ function is called by the import statement. Its signature is:

__import__(name[, globals[, locals[, fromlist[, level]]]])

Parameters description:

name (required): name of the module to load.

globals (optional): dictionary of global variables, rarely used, defaults to globals() .

locals (optional): dictionary of local variables, not used by the standard implementation, defaults to locals() .

fromlist (optional): names of submodules to import.

level (optional): import level; -1 in Python 2 (both absolute and relative), 0 in Python 3 (absolute only), >0 for relative imports.

Example:

>> os = __import__('os')
>>> os.getcwd()
'/home/wangbm'

To achieve import xx as yy, assign the result to a new name.

>> myos = __import__('os')
>>> myos.getcwd()
'/home/wangbm'

3. Using importlib

importlib

is a standard library providing comprehensive import functionality.

Simple example:

>> import importlib
>>> myos = importlib.import_module("os")
>>> myos.getcwd()
'/home/wangbm'

To mimic import xx as yy, assign the returned module to a new variable.

4. Using imp

The imp module offers low‑level import interfaces such as find_module and load_module. Example:

>> import imp
>>> file, pathname, desc = imp.find_module('os')
>>> myos = imp.load_module('sep', file, pathname, desc)
>>> myos.getcwd()
'/home/wangbm'

Note: imp is deprecated since Python 3.4; its functionality moved to importlib.

5. Using execfile (Python 2 only)

execfile

executes a file's contents. execfile(filename[, globals[, locals]]) Parameters: filename, optional globals dict, optional locals mapping.

>> execfile("/usr/lib64/python2.7/os.py")
>>> getcwd()
'/home/wangbm'

6. Using exec (Python 2 only)

exec

can run code read from a file.

with open("/usr/lib64/python2.7/os.py", "r") as f:
    exec(f.read())
>>> getcwd()
'/home/wangbm'

7. import_from_github_com package

This third‑party package installs a module from GitHub via pip and then imports it using __import__.

$ python3 -m pip install import_from_github_com
$ python3 -m pip install --upgrade pip

After installation you can import a package directly from GitHub:

>> from github_com.zzzeek import sqlalchemy
Collecting git+https://github.com/zzzeek/sqlalchemy
...
Successfully installed SQLAlchemy-1.1.0b1.dev0

8. Remote module import

A custom meta‑path finder can load modules over HTTP. Example implementation ( my_importer.py) defines UrlMetaFinder and UrlMetaLoader classes that fetch .py files from a base URL.

# my_importer.py
import sys, importlib, urllib.request as urllib2

class UrlMetaFinder(importlib.abc.MetaPathFinder):
    def __init__(self, baseurl):
        self._baseurl = baseurl
    def find_module(self, fullname, path=None):
        if path is None:
            baseurl = self._baseurl
        else:
            if not path.startswith(self._baseurl):
                return None
            baseurl = path
        try:
            loader = UrlMetaLoader(baseurl)
            return loader
        except Exception:
            return None

class UrlMetaLoader(importlib.abc.SourceLoader):
    def __init__(self, baseurl):
        self.baseurl = baseurl
    def get_code(self, fullname):
        f = urllib2.urlopen(self.get_filename(fullname))
        return f.read()
    def get_filename(self, fullname):
        return self.baseurl + fullname + '.py'

def install_meta(address):
    finder = UrlMetaFinder(address)
    sys.meta_path.append(finder)

Running a local HTTP server and registering the finder enables importing a remote module:

>> from my_importer import install_meta
>>> install_meta('http://localhost:12800/')
>>> import my_info
ok
>>> my_info.name
'wangbm'

All eight methods are presented; for most developers the simple import statement suffices, while deeper understanding of __import__ and importlib benefits framework authors.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonmodule loadingdynamic importImportimportlib
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.