Skip to main content

ImportSpy is a lightweight Python library that enables proactive control over how your code is used when imported by other modules or packages. It allows developers to define rules that importing modules must follow, ensuring proper use and preventing misuse or errors.

Project description

https://static.pepy.tech/badge/importspy https://img.shields.io/github/actions/workflow/status/atellaluca/ImportSpy/python-package.yml?style=flat-square https://img.shields.io/github/license/atellaluca/ImportSpy?style=flat-square

ImportSpy

ImportSpy Image

ImportSpy

ImportSpy is the ultimate Python library for proactive import control. Designed for complex and modular environments, ImportSpy ensures that external modules adhere to precise rules, improving the stability and security of your project.

Why ImportSpy?

ImportSpy allows developers to:

  • Define clear rules: Specify required functions, classes, and environment variables for every module importing your code.

  • Validate imports: Ensure external modules comply with these rules before they can interact with your code.

  • Improve project quality: Reduce bugs caused by improper imports or misconfigured environments.

Key Features

🔒 Proactive Import Validation

Define what an external module must include to import your code:
  • Required functions and classes.

  • Mandatory methods and attributes.

  • Structural dependencies such as superclasses.

📋 Environment Variable Validation

Ensure the environment is correctly configured:
  • Check for critical environment variables.

  • Validate their values against predefined expectations.

  • Essential for CI/CD pipelines or distributed systems.

🧩 Optimized for Modular Architectures

Supports complex systems:
  • Prevents cyclic dependencies.

  • Facilitates seamless integration of plugins and scalable components.

🔄 Import Monitoring

Gather data on how modules interact with your code:
  • Track external imports.

  • Provide valuable debugging insights.

Installation

You can install ImportSpy via PyPI with a single command:

pip install importspy

Quick Start

Defining Validation Rules

Start by creating a SpyModel that defines what is expected from modules importing your code:

from importspy import Spy
from importspy.models import SpyModel, ClassModel
from typing import List, Optional


class MyLibrarySpy(SpyModel):
    # Name of the expected module file
    filename: Optional[str] = "expected_module.py"

    # Expected version of the module
    version: Optional[str] = "1.0.0"

    # Required variables defined within the module (name-value pairs)
    variables: dict = {
        "default_timeout": "30",
        "max_connections": "100"
    }

    # Required functions
    functions: List[str] = ["process_data", "log_results"]

    # Required classes
    classes: List[ClassModel] = [
        ClassModel(
            name="DataProcessor",  # Class name
            class_attr=["processor_type", "status"],  # Required class-level attributes
            instance_attr=["input_data", "output_data"],  # Required instance-level attributes
            methods=["process", "save"],  # Required methods
            superclasses=["BaseProcessor"]  # Expected superclasses
        ),
        ClassModel(
            name="Logger",
            class_attr=["log_level"],
            instance_attr=["log_file"],
            methods=["log_message", "clear_logs"],
            superclasses=[]
        )
    ]

    # Required environment variables
    env_vars: dict = {
        "CI": "true",
        "DATA_PATH": "/data/"
    }

Validating During Import

Use ImportSpy to validate a module:

spy = Spy()

try:
    module = spy.importspy(spymodel=MyLibrarySpy)
    print(f"Module '{module.__name__}' complies with the specified rules.")
except ValueError as ve:
    print(f"Validation error: {ve}")

Real-World Use Cases

CI/CD Pipelines

Ensure the CI/CD environment has all the required variables:

env_vars: dict = {
    "CI": "true",
    "GITHUB_ACTIONS": "true"
}

Outcome: Prevent errors caused by misconfigurations.

Plugin-Based Systems

Ensure each plugin properly implements the required classes:

classes: List[ClassModel] = [
    ClassModel(name="PluginInterface", methods=["initialize", "execute"])
]

Outcome: Smooth and predictable integration.

Modular Projects

Avoid structural errors by defining rules for essential functions and attributes:

functions: List[str] = ["init_module", "shutdown"]

Outcome: Improved project stability and code quality.

How It Works

  1. Define Rules: Use SpyModel to specify requirements.

  2. Module Import: When a module is imported, ImportSpy validates that the rules are met.

  3. Validation Outcome: - Success: The import proceeds without issues. - Failure: A descriptive error is raised.

Why Choose ImportSpy?

  • Enhances Security: Blocks non-compliant imports, reducing the risk of bugs and vulnerabilities.

  • Simplifies Debugging: Easily trace incorrect imports.

  • Supports Code Evolution: Write code that defines rules for future integrations, preventing errors before they occur.

Support the Development of ImportSpy

ImportSpy is an open-source project passionately developed by a single developer from Satriano di Lucania, a small town in the beautiful region of Lucania, Italy. This project represents a unique solution for managing Python imports, but it requires time, dedication, and resources to grow and improve.

Why Your Support Matters

By sponsoring ImportSpy, you can help:

  • Accelerate development: Your support allows me to dedicate more time to creating new features, fixing bugs, and improving compatibility.

  • Keep the project up to date: Ensure ImportSpy continues to support the latest Python versions and modern development needs.

  • Provide community support: Expand documentation, create advanced examples, and respond to user inquiries.

  • Make the project sustainable: Promote innovation in an open-source environment.

Every contribution, big or small, makes a difference and helps keep the project free and accessible for everyone.

How to Sponsor

You can sponsor ImportSpy directly on GitHub. As a sponsor, you will:

  • Be publicly recognized (if desired) in the documentation and GitHub repository.

  • Influence project development by suggesting features that meet your needs.

  • Receive priority support for integrating ImportSpy into your projects.

💡 Sponsor ImportSpy now: GitHub Sponsors

A Small Contribution, A Big Impact

Your support is not just an investment in ImportSpy but also in the open-source philosophy, which fosters innovation and collaboration within the Python community. Even a small contribution can make a big difference!

Thank you for believing in this project and helping take ImportSpy to the next level. ❤️

Access the Full Documentation

For detailed guidance on using ImportSpy, including advanced usage, API references, and examples, visit our official documentation.

The documentation is continually updated to ensure you have access to the latest features, best practices, and integration tips. Whether you’re a beginner or an experienced developer, the documentation will help you unlock the full potential of ImportSpy.

Contribute to ImportSpy

Want to contribute? Add new features, provide feedback, or report bugs.

License

This project is distributed under the MIT License. See the LICENSE file for details.

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

importspy-0.1.11.tar.gz (15.4 kB view details)

Uploaded Source

Built Distribution

importspy-0.1.11-py3-none-any.whl (14.7 kB view details)

Uploaded Python 3

File details

Details for the file importspy-0.1.11.tar.gz.

File metadata

  • Download URL: importspy-0.1.11.tar.gz
  • Upload date:
  • Size: 15.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.12.7 Linux/6.11.7-200.fc40.x86_64

File hashes

Hashes for importspy-0.1.11.tar.gz
Algorithm Hash digest
SHA256 f80dcc7b806299af4b813fafaef4336b75e1fdaa82e3a0533663b7675dabeb71
MD5 becc069ca89f4782c36d833a01423a52
BLAKE2b-256 8ef3eae086d51e24b6dda9b7bf3eb4ed3e2615a69ee6a10d803a293bcea16b78

See more details on using hashes here.

File details

Details for the file importspy-0.1.11-py3-none-any.whl.

File metadata

  • Download URL: importspy-0.1.11-py3-none-any.whl
  • Upload date:
  • Size: 14.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.12.7 Linux/6.11.7-200.fc40.x86_64

File hashes

Hashes for importspy-0.1.11-py3-none-any.whl
Algorithm Hash digest
SHA256 c998f5b80847ca5c0ad24850c851e6b7c41c015f61e6600cf924b57952d5968a
MD5 a44e9dbe8cf809ce751de18ce77882fa
BLAKE2b-256 43f6b6079989d3c85ff3cdd00d974aa2d49af9d6fd45a54207d5eba4c73929e0

See more details on using hashes here.

Supported by

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