A tool to monitor and trace module imports in Python projects.
Project description
ImportSpy
ImportSpy is a Python package designed to monitor, validate, and dynamically manage module imports in real-time. With its robust features, it excels in plugin-based architectures, offering dynamic module re-importing, customizable validation, and recursion detection, making your code more modular, secure, and efficient.
Table of Contents
- Key Features
- SpyModel: A Powerful Tool for Code Validation
- Use Cases
- Installation
- Documentation
- How to Use ImportSpy
- Usage Example
- Handling Dynamic Imports and Recursion
- Why Use ImportSpy?
- Contributing
- Donations and Sponsorship
- License
- Contact
Key Features
- Dynamic Import with Validation: Re-import modules dynamically and validate their content with custom models, ensuring that they meet your project’s structural and functional requirements.
- SpyModel for Full Python Code Modeling and Retroactive Validation: Define and validate the expected structure of Python code—including file names, versions, functions, and classes—and apply retroactive validation to ensure imported code adheres to required standards, even if written without prior validation considerations.
- Recursion Detection: Automatically detects and prevents recursion by raising an error when a module attempts to import itself.
- Stack Inspection: Trace import origins by inspecting the call stack, facilitating debugging and import tracking.
- Plugin Isolation: Perfect for plugin-based systems, ImportSpy isolates and validates plugins before integration, enhancing system modularity and stability.
SpyModel: A Powerful Tool for Code Validation and Retroactive Compatibility
The SpyModel
class in ImportSpy serves a critical role in ensuring that the code written by developers is fully compatible and executable when imported by other modules. It allows you to retroactively validate and enforce rules on existing code, ensuring that the imported code conforms to the expected structure and behavior. This means that even if the code was written without specific validation in mind, SpyModel
makes it possible to retroactively apply those validations when the code is imported into other modules.
SpyModel Attributes
- filename: (Optional[str]) – Specifies the file name of the module to be imported, ensuring the correct module is being validated.
- version: (Optional[str]) – Enforces version control by ensuring that the imported module matches a specific version, which is critical when working with different versions of a library or module.
- functions: (Optional[List[str]]) – Defines a list of required functions that must be present in the imported module. This ensures that even pre-existing code meets functional expectations when imported.
- classes: (Optional[List[ClassModel]]) – A list of class models that define the required classes and their methods. This ensures that existing classes in the imported module contain the necessary methods and behaviors required by the importing module.
Example of Retroactive Code Validation with SpyModel
from importspy import Spy
from importspy.models import SpyModel, ClassModel
from typing import List
# Define validation model for retroactive code validation
class PluginSpy(SpyModel):
filename: str = "my_plugin.py"
version: str = "1.0"
functions: List[str] = ["setup", "teardown"] # Ensure these functions exist
classes: List[ClassModel] = [
ClassModel(
name="MyPluginClass",
methods=["initialize", "shutdown"] # Ensure these methods exist in the class
)
]
# Use Spy to dynamically import and validate the module based on the retroactive model
module = Spy().importspy(spymodel=PluginSpy)
if module:
print(f"Module {module.__name__} imported and validated retroactively!")
else:
print("Module import failed retroactive validation.")
How SpyModel Works Retroactively
- Retroactive Enforcement: Even if the code was written without specific validation,
SpyModel
can enforce compatibility rules when that code is imported into other modules. This enables developers to ensure the compatibility of legacy or third-party code without needing to modify the original codebase. - Dynamic Adaptation: The importing module can specify which functions, classes, or methods the imported module should contain, ensuring the module behaves as expected without needing direct modifications.
Use Cases
- Dynamic Code Validation: Ensure imported modules conform to predefined structures using
SpyModel
. - Plugin-Based Architectures: Validate and isolate plugins before integration to ensure system stability.
- Version-Specific Imports: Ensure compatibility by enforcing version requirements on imported modules.
Installation
Install ImportSpy with pip:
pip install importspy
Documentation
Detailed documentation and advanced usage examples can be found here.
How to Use ImportSpy
- Create a
Spy
instance and configure it with a validation model orSpyModel
to define what the module should contain. - Import the module using
importspy
and pass the validation function orSpyModel
to check its structure or content. - Handle recursion errors if a module attempts to import itself, raising a
ValueError
to avoid infinite loops.
Usage Example
from importspy import Spy
from importspy.models import SpyModel, ClassModel
from typing import List
class PluginSpy(SpyModel):
filename: str = "my_plugin.py"
version: str = "1.0"
functions: List[str] = ["setup", "teardown"]
classes: List[ClassModel] = [
ClassModel(name="MyPluginClass", methods=["initialize", "shutdown"])
]
module = Spy().importspy(spymodel=PluginSpy)
if module:
print(f"Module {module.__name__} imported successfully!")
else:
print("Module import failed validation.")
Handling Dynamic Imports and Recursion
ImportSpy uses importlib
and inspect
to manage dynamic imports and detect recursion, ensuring that modules are imported safely and meet the required criteria.
Why Use ImportSpy?
ImportSpy provides powerful control over how modules are imported and validated, making it an essential tool for modular applications, plugin systems, and projects with dynamic dependencies.
Contributing
We welcome contributions! Feel free to open issues or submit pull requests. See the CONTRIBUTING.md
file for more details.
Donations and Sponsorship
If you find ImportSpy useful and would like to support its continued development, consider sponsoring or donating:
- GitHub Sponsors: Sponsor this project on GitHub
- PayPal: Donate via PayPal
Your support helps us maintain and improve the project. Thank you!
License
This project is licensed under the MIT License.
Contact
For questions, feel free to reach out via the GitHub repository.
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
Hashes for importspy-0.1.6-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | a135abde6b3508eb2955553a658a29cec91bff69d43d96d6ca45f81c7624145a |
|
MD5 | 126225b45dbd2ad98e4694f833da28d2 |
|
BLAKE2b-256 | 7731d19682f21d5df762115aabce7de406d0fc8cf7f563aae7f5dcc7c6d8ebef |