Load a named standard-library module with importlib

importlib.import_module() imports a module from a string name and returns that requested module. This is useful when a program selects from a controlled dispatch table or configuration value. Here, the concrete input is the string "statistics". The returned module provides mean(), which receives [2, 4, 6]; the assertion verifies that this calculation produces 4 before the program prints two stable lines.

The example intentionally names a standard-library module, so it needs no local fixture or network access. import_module() accepts absolute names and can resolve relative names when a package anchor is supplied. It is a programmatic-import interface, not a validator for arbitrary plugin names: importing executes module-level code. An application should restrict or validate names obtained from untrusted input before importing them. The assertion establishes this one calculation in the running interpreter; it does not establish that every attribute of the imported module is suitable for an application.

The importlib package was added in Python 3.1. The documentation recommends import_module() rather than calling __import__() directly for programmatic imports. See the Python importlib documentation.

import importlib

module = importlib.import_module("statistics")
result = module.mean([2, 4, 6])

assert result == 4
print(f"module: {module.__name__}")
print(f"mean: {result}")
module: statistics
mean: 4

AI-assistance disclosure: AI helped draft this explanation and example.

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic