Python Path Context Manager

0.1.3 · maintenance · verified Thu Apr 16

The `python-path` library (version 0.1.3, last updated in 2018) provides a simple context manager for temporarily modifying `sys.path`. It offers a clean way to add directories to Python's import search path, allowing scripts to import modules located in other folders without permanent global modifications. This is particularly useful for safely loading local scripts or modules from dynamically determined paths. The project's release cadence appears inactive.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `PythonPath` context manager to temporarily add a directory to `sys.path` for importing modules, and how `sys.path` is automatically restored upon exiting the `with` block.

import os
from python_path import PythonPath

# Create a dummy module in a temporary directory
temp_dir = "./temp_modules"
os.makedirs(temp_dir, exist_ok=True)
with open(os.path.join(temp_dir, "my_module.py"), "w") as f:
    f.write("def greet():\n    return \"Hello from my_module!\"")

# Attempt to import without modifying sys.path (will fail)
try:
    import my_module
except ImportError as e:
    print(f"Expected error: {e}")

# Use PythonPath context manager to add the directory to sys.path
with PythonPath(temp_dir):
    import my_module
    print(my_module.greet())

# After exiting the 'with' block, my_module is no longer importable (sys.path restored)
try:
    import my_module
except ImportError as e:
    print(f"Expected error after context exit: {e}")

# Clean up the dummy module and directory
os.remove(os.path.join(temp_dir, "my_module.py"))
os.rmdir(temp_dir)

view raw JSON →