A Python context manager for temporarily adding and removing paths from sys.path
Project description
Dynamic Path Manager
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.pathclear_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 occurredexc_val: Exception value if an exception occurredexc_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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file dynamic_path_manager-1.0.1.tar.gz.
File metadata
- Download URL: dynamic_path_manager-1.0.1.tar.gz
- Upload date:
- Size: 24.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
efd1b16aabaa0c14b8a8b6756c9bea80c82ccff7fd87b3cdc7528bb1ee88088c
|
|
| MD5 |
5938d940c1848c3106ec8638f309dc5d
|
|
| BLAKE2b-256 |
5272e8678f6a70386aea2ebf123178e0ce416c092d7ea49c66d435fd43834200
|
File details
Details for the file dynamic_path_manager-1.0.1-py3-none-any.whl.
File metadata
- Download URL: dynamic_path_manager-1.0.1-py3-none-any.whl
- Upload date:
- Size: 7.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bfb15bd7df1ce932798d9a6acb1784efe040888202d8613c4356ddee5b00dc91
|
|
| MD5 |
cf1802145de6d2fd7fa780f9e7a3dfa9
|
|
| BLAKE2b-256 |
82cae539573e79ebd00cebe4681b3b7ae9296c0851b7d13a72b6bae515f5b9d5
|