Skip to main content

A Python context manager for temporarily adding and removing paths from sys.path

Project description

Dynamic Path Manager

Python Version License Build Status

A Python context manager for temporarily adding and removing paths from sys.path. This is particularly useful when you need to dynamically import modules from different directories without permanently polluting your Python path.

Features

  • 🚀 Simple Context Manager: Easy-to-use context manager interface
  • 🧹 Automatic Cleanup: Automatically removes paths when exiting the context
  • 🔄 Module Cache Management: Clears module cache to prevent conflicts
  • 🛡️ Safe: Only removes paths that were added by the manager
  • 📦 Lightweight: No external dependencies
  • 🐍 Python 3.7+: Compatible with modern Python versions

Installation

pip install dynamic-path-manager

Or install from source:

git clone https://github.com/yourusername/dynamic-path-manager.git
cd dynamic-path-manager
pip install -e .

Quick Start

from dynamic_path_manager import DynamicPathManager

# Temporarily add a path to sys.path
with DynamicPathManager("./my_package") as manager:
    from my_module import some_function
    result = some_function()
    print(f"Result: {result}")

# Path is automatically removed from sys.path after the with block

Usage Examples

Basic Usage

from dynamic_path_manager import DynamicPathManager

with DynamicPathManager("./examples/a") as manager:
    from utils.helper import f
    f()  # Output: a.utils.helper

with DynamicPathManager("./examples/b") as manager:
    from utils.helper import f
    f()  # Output: b.utils.helper

Advanced Usage

from dynamic_path_manager import DynamicPathManager

# Disable cache clearing if you want to keep modules in memory
with DynamicPathManager("./my_package", clear_cache=False) as manager:
    from my_module import expensive_function
    result = expensive_function()

# Check if path is in sys.path
if manager.is_path_in_sys_path():
    print("Path is currently in sys.path")

# Get the managed path
print(f"Managed path: {manager.get_path()}")

Error Handling

from dynamic_path_manager import DynamicPathManager

try:
    with DynamicPathManager("./nonexistent_path") as manager:
        from some_module import function
        function()
except ImportError as e:
    print(f"Failed to import: {e}")
# Path is still cleaned up even if an exception occurs

API Reference

DynamicPathManager

__init__(package_path: str, clear_cache: bool = True)

Initialize the Dynamic Path Manager.

Parameters:

  • package_path (str): The path to add to sys.path
  • clear_cache (bool): Whether to clear module cache on exit (default: True)

__enter__() -> DynamicPathManager

Enter the context manager and add the path to sys.path.

Returns:

  • DynamicPathManager: The instance itself

__exit__(exc_type, exc_val, exc_tb) -> None

Exit the context manager and clean up.

Parameters:

  • exc_type: Exception type if an exception occurred
  • exc_val: Exception value if an exception occurred
  • exc_tb: Exception traceback if an exception occurred

get_path() -> str

Get the absolute path being managed.

Returns:

  • str: The absolute path

is_path_in_sys_path() -> bool

Check if the managed path is currently in sys.path.

Returns:

  • bool: True if the path is in sys.path, False otherwise

Use Cases

  • Plugin Systems: Dynamically load plugins from different directories
  • Testing: Import test modules from various locations
  • Development: Switch between different versions of modules
  • Package Management: Temporarily use local versions of packages
  • Microservices: Import modules from service-specific directories

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Development

To set up a development environment:

git clone https://github.com/yourusername/dynamic-path-manager.git
cd dynamic-path-manager
pip install -e ".[dev]"

Run tests:

pytest

Run linting:

flake8 src/
black src/

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

1.0.0 (2024-01-XX)

  • Initial release
  • Basic context manager functionality
  • Module cache management
  • Comprehensive documentation

Acknowledgments

  • Inspired by the need for clean dynamic imports in Python projects
  • Thanks to the Python community for the excellent tooling and documentation

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dynamic_path_manager-1.0.0.tar.gz (14.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dynamic_path_manager-1.0.0-py3-none-any.whl (7.1 kB view details)

Uploaded Python 3

File details

Details for the file dynamic_path_manager-1.0.0.tar.gz.

File metadata

  • Download URL: dynamic_path_manager-1.0.0.tar.gz
  • Upload date:
  • Size: 14.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for dynamic_path_manager-1.0.0.tar.gz
Algorithm Hash digest
SHA256 97241c88de1435d5efc20be7164ed67802840b7b7f7a88496d5bc29afb2c80df
MD5 3971ce21118deeba5535e12999d1adc5
BLAKE2b-256 42db49f1d5d42f6ade136c9f08a347c28005a75c7b2526c02b82601a8a987c4c

See more details on using hashes here.

File details

Details for the file dynamic_path_manager-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for dynamic_path_manager-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e57f0679ab3fdb8344a7bb7a237654d46473e5546b8363e161bf9c6b0c3a58f1
MD5 e5070e73a00fbf2709f494fdc2ab5cf4
BLAKE2b-256 3ad9bffae06b12a455ffc1869e4229453f0bcf1eaf6d3b72bdd81ad06a8f1ac4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page