{"library":"maturin-import-hook","title":"Maturin Import Hook","description":"The maturin-import-hook library provides a Python import hook for projects built with `maturin`, allowing Python code to dynamically load and use Rust modules without needing an `editable` install or pre-building. It simplifies development workflows for mixed Python/Rust projects by building the Rust extension on demand. The current version is 0.3.0, and it generally follows a bug-fix driven release cadence with support for new Python versions.","language":"python","status":"active","last_verified":"Thu Apr 16","install":{"commands":["pip install maturin-import-hook","pip install maturin"],"cli":null},"imports":["import maturin_import_hook; maturin_import_hook.install()"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import maturin_import_hook\nimport sys\nimport os\nimport shutil\n\n# This hook allows Python to find and load Rust modules\n# defined in a maturin project within the current directory\n# or a parent directory.\nmaturin_import_hook.install()\n\n# --- Setup a dummy Rust project for demonstration ---\n# In a real project, this setup would already exist.\nproject_name = \"my_rust_module\"\nproject_dir = \"temp_rust_project\"\nmodule_path = os.path.join(project_dir, \"src\")\n\n# Clean up any previous run's artifacts\nif os.path.exists(project_dir):\n    shutil.rmtree(project_dir)\n\nos.makedirs(module_path, exist_ok=True)\n\n# Create pyproject.toml\nwith open(os.path.join(project_dir, \"pyproject.toml\"), \"w\") as f:\n    f.write(f\"\"\"\n[project]\nname = \"{project_name}\"\nversion = \"0.1.0\"\n\n[tool.maturin]\nname = \"{project_name}\"\nbindings = \"pyo3\"\n    \"\"\")\n\n# Create Cargo.toml (maturin can infer some parts, but explicit is clearer for quickstart)\nwith open(os.path.join(project_dir, \"Cargo.toml\"), \"w\") as f:\n    f.write(f\"\"\"\n[package]\nname = \"{project_name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[lib]\nname = \"{project_name}\"\ncrate-type = [\"cdylib\"]\n\n[dependencies]\npyo3 = {{ version = \"0.20\", features = [\"extension-module\"] }}\n    \"\"\")\n\n\n# Create src/lib.rs with a simple PyO3 function\nwith open(os.path.join(module_path, \"lib.rs\"), \"w\") as f:\n    f.write(\"\"\"\nuse pyo3::prelude::*;\n\n#[pyfunction]\nfn greet() -> PyResult<String> {\n    Ok(\"Hello from Rust!\".to_string())\n}\n\n#[pymodule]\nfn my_rust_module(_py: Python<'_>, m: &PyModule) -> PyResult<()> {\n    m.add_function(wrap_pyfunction!(greet, m)?)?;\n    Ok(())\n}\n        \"\"\")\n\n# Change to the project directory so the hook can find pyproject.toml\noriginal_cwd = os.getcwd()\nos.chdir(project_dir)\n\nprint(f\"Attempting to import '{project_name}' from: {os.getcwd()}\")\n\n# Now, import the Rust module as if it were a Python module\n# The hook will find pyproject.toml and potentially build the module.\ntry:\n    import my_rust_module\n    message = my_rust_module.greet()\n    print(f\"✅ Successfully imported and called Rust module: {message}\")\nexcept ImportError as e:\n    print(f\"❌ Failed to import Rust module: {e}\", file=sys.stderr)\n    print(\"Ensure 'maturin' is installed (pip install maturin) and your Rust project is valid.\", file=sys.stderr)\nexcept Exception as e:\n    print(f\"❌ An unexpected error occurred: {e}\", file=sys.stderr)\nfinally:\n    # Clean up dummy project and restore original cwd\n    os.chdir(original_cwd)\n    if os.path.exists(project_dir):\n        print(f\"Cleaning up temporary project directory: {project_dir}\")\n        shutil.rmtree(project_dir)\n","lang":"python","description":"Demonstrates how to use `maturin-import-hook` to dynamically load a Rust module defined in a `maturin` project. It sets up a minimal Rust project with a `pyproject.toml` and `src/lib.rs`, installs the hook, imports the Rust module, calls a function, and then cleans up. This example assumes `maturin` is already installed in your environment.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}