Skip to main content

Python Import Rewriter

A flexible library for dynamically rewriting Python imports at runtime using metapath hooks.

Hatch project Tests PyPI version PyPI Supported Python Versions Downloads

Overview

Import Rewriter allows you to transparently redirect imports in Python code without modifying the source. This is useful for:

  • Providing mock implementations during testing
  • Implementing feature toggles or A/B testing at the module level
  • Creating compatibility layers for different library versions
  • Redirecting imports for dependency injection
  • Implementing module aliases for refactoring
  • Vendoring dependencies at runtime

The library works by intercepting the Python import system using metapath hooks and rewriting the import statements in the Abstract Syntax Tree (AST) before execution.

Installation

pip install import-rewriter

Quick Start

from import_rewriter import install_import_rewriter

# Redirect imports of 'legacy_module' to use 'modern_module' instead
install_import_rewriter({
    'legacy_module': 'modern_module',
    'requests': 'my_custom_requests'
})

# Now when your code does:
import legacy_module
# It will actually import 'modern_module'

Features

  • Transparently rewrites imports without changing the original code
  • Handles both import x and from x import y statements
  • Can be enabled/disabled at runtime
  • Minimal performance impact for non-rewritten imports
  • Works with standard Python imports, no special syntax required
  • Preserves import aliases (import x as y)

API Reference

install_import_rewriter(import_map=None)

Installs the import rewriting hook with the specified mapping.

Parameters:

  • import_map (dict): A dictionary mapping original import names to replacement names.

Returns:

  • The finder instance that was installed (can be used to uninstall later).

Example:

finder = install_import_rewriter({
    'pandas': 'custom_pandas',
    'tensorflow': 'tensorflow_lite'
})

Uninstalling the Hook

To remove the hook and restore normal import behavior:

import sys
sys.meta_path.remove(finder)

Advanced Usage

Selective Module Rewriting

You can selectively rewrite imports for specific modules or packages:

install_import_rewriter({
    'pandas.DataFrame': 'my_package.DataFrame',
    'numpy.array': 'my_package.fast_array'
})

Dynamic Rewriting

You can change the import mapping at runtime:

finder = install_import_rewriter()
finder.import_map['requests'] = 'mock_requests'  # Add new mapping

How It Works

Import Rewriter uses three key components:

  1. MetaPath Finder: Intercepts import requests before they're processed by the standard import machinery.
  2. AST Transformer: Parses and modifies the abstract syntax tree of the source code.
  3. Custom Loader: Executes the modified code in the module's namespace.

When a module is imported, the finder intercepts the request, the transformer rewrites any matching imports, and the loader executes the modified code.

Limitations

  • Only rewrites imports in modules that are loaded after the hook is installed
  • Cannot rewrite imports in c-extensions, built-in, or frozen modules
  • May have unpredictable interactions with other import hooks

License

GPLv3

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Metadata

Release files for import-rewriter 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for import-rewriter 1.0.0
File Size Uploaded Provenance Actions
import_rewriter-1.0.0.tar.gz 42.4 kB With provenance Details for import_rewriter-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for import-rewriter 1.0.0
File Interpreter ABI Platform Actions
import_rewriter-1.0.0-py3-none-any.whl Python 3 none any Details for import_rewriter-1.0.0-py3-none-any.whl

Total release size: 71.9 kB

Release files / import_rewriter-1.0.0.tar.gz

Download URL import_rewriter-1.0.0.tar.gz
Size 42.4 kB
Tags Source
SHA-256 checksum
How to use checksums
6f2c16992611f303b2873338bedf55d0e2d3e11a74cb0f6b88dbbcbec5eecde4
BLAKE2b-256 checksum
How to use checksums
1f89f5e0a4aecbf7264d64bf747700f8374128748cb48a18182ecfb19ed1dbc7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 31, 2025.

Transparency log

Release files / import_rewriter-1.0.0-py3-none-any.whl

Download URL import_rewriter-1.0.0-py3-none-any.whl
Size 29.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e0fc1c6d898c1300265814792b5803aa560c91b7289e937263e399dcbbf4891c
BLAKE2b-256 checksum
How to use checksums
ddb67478d93ee892940a3f9affcd642e502059e03c8485a9be5cc0be44d504c9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.12.9

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 31, 2025.

Transparency log

Security for import-rewriter 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for import_rewriter-1.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Mar 31, 2025.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page