Skip to content

API Reference

This section documents the public Python API exposed by ImportSpy, organized by module.
All components listed here are available when you install the package.

importspy.s

Core validation logic for ImportSpy.

This module defines the Spy class, the central component responsible for dynamically inspecting and validating Python modules against import contracts (YAML files that declare expected structure and execution context).

The validation can be triggered in two ways:

  • Embedded validation: when the Spy is embedded inside a core module and validates its importer.
  • External validation (CLI/pipeline): when a separate process uses Spy to check a module before runtime.

Validation covers classes, attributes, functions, and environmental settings like OS, Python version, and interpreter.

This module is typically used as the entry point for programmatic validation workflows.

Spy

Core validation engine for ImportSpy.

The Spy class is responsible for loading a target module, extracting its structure, and validating it against a YAML-based import contract. This ensures that the importing module satisfies all declared structural and runtime constraints.

It supports two modes: - Embedded mode: validates the caller of the current module - External/CLI mode: validates an explicitly provided module

Attributes:

logger : logging.Logger Structured logger for validation diagnostics.

Parser

Parser used to load import contracts (defaults to YAML).

__init__()

Initialize the Spy instance.

Sets up: - a dedicated logger - the default YAML parser

importspy(filepath=None, log_level=None, info_module=None)

Main entry point for validation.

Loads and validates a Python module against the contract defined in the given YAML file. If no module is explicitly provided, introspects the call stack to infer the caller.

Parameters:

filepath : Optional[str] Path to the .yml import contract.

Optional[int]

Log verbosity level (e.g., logging.DEBUG).

Optional[ModuleType]

The module to validate. If None, uses the importer via stack inspection.

Returns:

ModuleType The validated module.

Raises:

RuntimeError If logging setup fails.

ValueError If recursion is detected (e.g., a module is validating itself).


importspy.models

models.py

Defines the structural and contextual data models used across ImportSpy. These models represent modules, variables, functions, classes, runtimes, systems, and environments involved in contract-based validation.

This module powers both embedded validation and CLI checks, enabling ImportSpy to introspect, serialize, and enforce compatibility rules at multiple levels: from source code structure to runtime platform details.

Argument

Bases: Variable, BaseModel

Represents a function/method argument.

Includes: - Name - Optional type annotation - Optional default value Used to check call signatures.

Attribute

Bases: Variable

Represents a class-level attribute.

Extends Variable with attribute type (e.g., class or instance).

Class

Bases: BaseModel

Represents a Python class declaration.

Includes: - Name - Attributes (class/instance) - Methods - Superclasses (recursive)

Environment

Bases: BaseModel

Represents runtime environment variables and secrets. Used for validating runtime configuration.

Error

Bases: BaseModel

Describes a structured validation error.

Includes the context, error type, message, and resolution steps. Used to serialize feedback during contract enforcement.

Function

Bases: BaseModel

Represents a callable entity.

Includes: - Name - List of arguments - Optional return annotation

Module

Bases: BaseModel

Represents a Python module.

Includes: - Filename - Version (if extractable) - Top-level variables, functions, and classes

Python

Bases: BaseModel

Represents a Python runtime environment.

Includes: - Python version - Interpreter type (e.g., CPython, PyPy) - List of loaded modules Used in validating runtime compatibility.

Runtime

Bases: BaseModel

Represents a runtime deployment context.

Defined by CPU architecture and associated systems.

SpyModel

Bases: Module

High-level model used by ImportSpy for validation.

Extends the module representation with runtime metadata and platform-specific deployment constraints (architecture, OS, interpreter, etc).

from_module(info_module) classmethod

Build a SpyModel instance by extracting structure and metadata from an actual Python module object.

System

Bases: BaseModel

Represents a full OS environment within a deployment system.

Includes: - OS type - Environment variables - Python runtimes Used to validate cross-platform compatibility.

Variable

Bases: BaseModel

Represents a top-level variable in a Python module.

Includes: - Name - Optional annotation - Optional static value Used to enforce structural consistency.


importspy.validators

ImportSpy Contract Validators

This module defines structural and runtime validators for comparing expected contract definitions against observed runtime representations.

Each validator compares a specific domain (e.g., Python version, environment variables, module structure, class layout) using ImportSpy's SpyModel structures.

If mismatches or missing elements are detected, specialized ContractViolation objects raise informative ValueError exceptions enriched with context bundles.

Used both in embedded runtime validation and CLI mode.

Validators
  • RuntimeValidator
  • SystemValidator
  • PythonValidator
  • ModuleValidator
  • ClassValidator
  • FunctionValidator
  • VariableValidator

ClassValidator

Validates class structure, attributes, and methods.

validate(classes_1, classes_2, contract_violation)

Recursively validate class structure and inheritance.

Parameters:

Name Type Description Default
classes_1 List[Class]

Expected class definitions.

required
classes_2 List[Class]

Observed runtime classes.

required
contract_violation BaseContractViolation

Shared context for error propagation.

required

Raises:

Type Description
ValueError

On missing class, method, or attribute mismatch.

FunctionValidator

Validates functions, their arguments, and return annotations.

validate(functions_1, functions_2, contract_violation)

Compare function definitions across two modules or classes.

Parameters:

Name Type Description Default
functions_1 List[Function]

Expected functions.

required
functions_2 List[Function]

Observed functions.

required
contract_violation BaseContractViolation

Violation context object.

required

Raises:

Type Description
ValueError

On missing, unmatched, or misannotated functions.

ModuleValidator

Validates modules, including structure, variables, functions, and classes.

validate(modules_1, module_2, contract_violation)

Validate module structure against expected SpyModel.

Parameters:

Name Type Description Default
modules_1 List[Module]

List of expected module definitions.

required
module_2 Module

Observed runtime module.

required
contract_violation ModuleContractViolation

Context bundle.

required

Raises:

Type Description
ValueError

On mismatch or missing module details.

PythonValidator

Validates Python version and interpreter compatibility.

validate(pythons_1, pythons_2, contract_violation)

Ensure that Python version/interpreter match expectations.

Parameters:

Name Type Description Default
pythons_1 List[Python]

Contract-defined expectations.

required
pythons_2 List[Python]

Runtime-detected Python instances.

required
contract_violation PythonContractViolation

Context bundle and error factory.

required

Returns:

Type Description
None

List[Module]: Modules associated with the matched Python.

Raises:

Type Description
ValueError

On missing or mismatched Python definitions.

RuntimeValidator

Validates architecture compatibility between runtime collections.

validate(runtimes_1, runtimes_2, contract_violation)

Compare runtime architectures and raise if no match is found.

Parameters:

Name Type Description Default
runtimes_1 List[Runtime]

Declared runtime requirements.

required
runtimes_2 List[Runtime]

Observed runtime environments.

required
contract_violation RuntimeContractViolation

Violation reporter instance.

required

Returns:

Name Type Description
Runtime None

The matching runtime, if found.

Raises:

Type Description
ValueError

If runtimes_2 is empty or no arch matches.

SystemValidator

Validates operating system and environment compatibility.

EnvironmentValidator

Validates environment-level variables and configuration.

validate(environment_1, environment_2, bundle)

Compare two environments' variable lists.

Parameters:

Name Type Description Default
environment_1 Environment

Expected environment.

required
environment_2 Environment

Observed environment.

required
bundle Bundle

Violation context and data.

required

Raises:

Type Description
ValueError

On missing or mismatched variables.

validate(systems_1, systems_2, contract_violation)

Compare systems and delegate to environment validation.

Parameters:

Name Type Description Default
systems_1 List[System]

Expected system definitions.

required
systems_2 List[System]

Runtime-observed systems.

required
contract_violation SystemContractViolation

Violation context and bundle.

required

Returns:

Type Description
None

List[Python]: Matching Python objects if validation passes.

Raises:

Type Description
ValueError

If no matching OS or missing environment.

VariableValidator

Validates variables, attributes, and annotations.

validate(variables_1, variables_2, contract_violation)

Validate variable existence, name, value, and annotation.

Parameters:

Name Type Description Default
variables_1 List[Variable]

Expected variables.

required
variables_2 List[Variable]

Actual runtime variables.

required
contract_violation VariableContractViolation

Violation and error builder.

required

Raises:

Type Description
ValueError

On missing or mismatched variables.


importspy.violation_systems

This module defines the hierarchy of contract violation classes used by ImportSpy.

Each violation type corresponds to a validation context (e.g., environment, runtime, module structure), and provides structured, human-readable error messages when the importing module does not meet the contract’s requirements.

The base interface ContractViolation defines the common error interface, while specialized classes like VariableContractViolation or RuntimeContractViolation define formatting logic for each scope.

Violations carry a dynamic Bundle object, which collects contextual metadata needed for formatting error messages and debugging failed imports.

BaseContractViolation

Bases: ContractViolation

Base implementation of a contract violation.

Includes default implementations of error formatting methods.

Bundle dataclass

Bases: MutableMapping

Shared mutable state passed to all violation handlers.

The bundle is a dynamic container used to inject contextual values (like module name, attribute name, or class name) into error templates.

ContractViolation

Bases: ABC

Abstract base interface for all contract violations.

Defines the core methods for rendering structured error messages, including context resolution and label generation.

Properties:

  • context: Validation context (e.g., environment, class, runtime)
  • label(spec): Retrieves the field name or reference used in error text.
  • missing_error_handler(spec): Formats error when required entity is missing.
  • mismatch_error_handler(expected, actual, spec): Formats error when values differ.
  • invalid_error_handler(allowed, found, spec): Formats error when a value is invalid.

FunctionContractViolation

Bases: BaseContractViolation

Contract violation handler for function signature mismatches.

ModuleContractViolation

Bases: BaseContractViolation

Contract violation handler for module-level mismatches (filename, version, structure).

PythonContractViolation

Bases: BaseContractViolation

Contract violation handler for Python version and interpreter mismatches.

RuntimeContractViolation

Bases: BaseContractViolation

Contract violation handler for runtime architecture mismatches.

SystemContractViolation

Bases: BaseContractViolation

Contract violation handler for system-level mismatches (OS, environment variables).

VariableContractViolation

Bases: BaseContractViolation

Contract violation handler for variables (module, class, environment, etc.).

Includes scope information to distinguish between types of variables.


importspy.persistences

Defines interfaces and implementations for handling import contracts
external YAML files used by ImportSpy to validate the structure and runtime expectations
of dynamically loaded Python modules.

Currently, only YAML is supported, but the architecture is extensible via the Parser interface.

All file I/O operations are wrapped in handle_persistence_error, ensuring clear error
messages in case of missing, malformed, or inaccessible contract files.

Parser

Bases: ABC

Abstract base class for import contract parsers.

Parsers are responsible for loading and saving .yml contract files that define a module’s structural and runtime expectations. This abstraction enables future support for additional formats (e.g., JSON, TOML).

Subclasses must implement save() and load().

load(filepath) abstractmethod

Parses a contract file and returns it as a dictionary.

Parameters:

filepath : str Path to the contract file on disk.

Returns:

dict Parsed contract data.

save(data, filepath) abstractmethod

Serializes the contract (as a dictionary) and writes it to disk.

Parameters:

data : dict Dictionary containing the contract structure.

str

Target path for saving the contract (typically .yml).

PersistenceError

Bases: Exception

Raised when contract loading or saving fails due to I/O or syntax issues.

This exception wraps low-level errors and provides human-readable feedback.

__init__(msg)

Initialize the error with a descriptive message.

Parameters:

msg : str Explanation of the failure.

YamlParser

Bases: Parser

YAML-based contract parser implementation.

Uses ruamel.yaml to read and write .yml files that define import contracts.
Preserves formatting, indentation, and quotes for consistent serialization.

__init__()

Initializes the YAML parser and configures output formatting.

load(filepath)

Loads and parses a .yml contract into a Python dictionary.

Parameters:

filepath : str Path to the contract file.

Returns:

dict Parsed contract structure.

save(data, filepath)

Saves a contract dictionary to a .yml file.

Parameters:

data : dict Contract structure.

str

Destination file path.

handle_persistence_error(func)

Decorator for wrapping parser I/O methods with user-friendly error handling.

Catches all exceptions and raises a PersistenceError with a generic message. This ensures ImportSpy fails gracefully if a contract file is missing, malformed, or inaccessible.

Parameters:

func : Callable The I/O method to wrap.

Returns:

Callable A wrapped version that raises PersistenceError on failure.


importspy.cli

Command-line interface (CLI) for validating Python modules against ImportSpy contracts.

This module defines the importspy CLI command, enabling local and automated validation of a Python file against a YAML-based SpyModel contract. It is designed for use in CI/CD pipelines, plugin systems, or developer workflows.

Features: - Loads and executes the specified Python module. - Parses the YAML contract file describing expected structure and runtime conditions. - Validates that the module complies with the declared interface and environment. - Provides user-friendly CLI feedback, including optional logging.

Use cases: - Enforcing structure of external plugins before loading. - Automating validation in GitHub Actions or other CI tools. - Assuring consistency in modular libraries or educational tools.

Example

importspy ./examples/my_plugin.py -s ./contracts/expected.yml --log-level DEBUG

Note

Validation is powered by the core Spy class. Validation errors are caught and displayed with enhanced CLI formatting.

handle_validation_error(func)

Decorator that formats validation errors for CLI output.

Intercepts ValueError raised by the Spy.importspy() call and presents the error reason in a readable, styled terminal message.

Used to wrap the main importspy() CLI command.

importspy(version=typer.Option(None, '--version', '-v', callback=(lambda value: show_version(value)), is_eager=True, help='Show the version and exit.'), modulepath=typer.Argument(str, help='Path to the Python module to load and validate.'), spymodel_path=typer.Option('spymodel.yml', '--spymodel', '-s', help='Path to the import contract file (.yml).'), log_level=typer.Option(None, '--log-level', '-l', help='Log level for output verbosity.'))

Validates a Python module against a YAML-defined SpyModel contract.

Parameters:

Name Type Description Default
version bool

Show ImportSpy version and exit.

Option(None, '--version', '-v', callback=lambda value: show_version(value), is_eager=True, help='Show the version and exit.')
modulepath str

Path to the Python module to validate.

Argument(str, help='Path to the Python module to load and validate.')
spymodel_path str

Path to the YAML contract file. Defaults to spymodel.yml.

Option('spymodel.yml', '--spymodel', '-s', help='Path to the import contract file (.yml).')
log_level LogLevel

Set logging verbosity (DEBUG, INFO, WARNING, ERROR).

Option(None, '--log-level', '-l', help='Log level for output verbosity.')

Returns:

Name Type Description
ModuleType ModuleType

The validated Python module (if compliant).

Raises:

Type Description
ValueError

If the module does not conform to the contract.

main()

CLI entry point.

Executes the importspy Typer app, allowing CLI usage like:

$ importspy my_module.py -s my_contract.yml

show_version(value)

Displays the current version of ImportSpy and exits the process.

Parameters:

Name Type Description Default
value bool

If True, prints the version and exits immediately.

required

importspy.constants

Constants

Canonical constants used by ImportSpy's runtime validation engine.

This class acts as a reference for valid architectures, operating systems, Python interpreters, structural types, and annotation labels. All values defined here represent the allowed forms of metadata used to verify import contracts.

Unlike Config, which reflects the current runtime, Constants provides the fixed set of values used for validation logic.

SupportedAnnotations

Bases: str, Enum

Supported type annotations for validation purposes.

SupportedArchitectures

Bases: str, Enum

Valid CPU architectures accepted in contracts.

SupportedClassAttributeTypes

Bases: str, Enum

Type of attribute in a class-level contract.

SupportedOS

Bases: str, Enum

Valid operating systems accepted in contracts.

SupportedPythonImplementations

Bases: str, Enum

Valid Python interpreter implementations.

Contexts

Bases: str, Enum

Context types used for contract validation.

These labels identify which layer of the system the error or constraint applies to.

Errors

Reusable error string templates and labels.

This utility provides consistent formatting for all error messages generated by ImportSpy. It supports singular and plural forms, as well as different validation categories: missing, mismatch, and invalid.

Category

Bases: str, Enum

Validation error types.


importspy.config

importspy.config

Static configuration definitions for ImportSpy.

This module declares platform-wide constants used throughout ImportSpy for validating compatibility and structural expectations declared in SpyModel contracts. These values represent the officially supported CPU architectures, operating systems, Python interpreters, version targets, class attribute types, and accepted type annotations.

Example

from importspy.config import Config Config.ARCH_X86_64 'x86_64' Config.INTERPRETER_CPYTHON 'CPython'

Config

Static configuration container for ImportSpy validation.

This class defines constants used during runtime and structural validation of Python modules. All values reflect supported targets or accepted types declared in .yml contracts interpreted by ImportSpy.

Attributes:

Name Type Description
Architectures str

Supported CPU architectures (e.g., "x86_64").

Operating Systems (str

Accepted OS identifiers (e.g., "linux").

Python Versions (str

Known compatible Python interpreter versions.

Interpreters str

Recognized Python implementation names.

Attribute Types (str

Whether class-level or instance-level variables.

Annotation Types (str

Type annotations allowed in contract validation.

These constants are typically used in: - Runtime environment checks - Contract-based validation - Enforcement of developer-specified constraints


importspy.log_manager

importspy.log_manager

Centralized logging system for ImportSpy.

This module defines logging utilities that ensure consistent formatting, traceability, and developer-friendly output across both embedded and CLI modes. The LogManager provides a global configuration entry point for logging, while CustomFormatter enhances each message with context such as file name, line number, and function.

Used in ImportSpy to provide high-fidelity logs during validation steps, contract resolution, and runtime introspection.

Example

from importspy.log_manager import LogManager log_manager = LogManager() log_manager.configure() logger = log_manager.get_logger("importspy.test") logger.info("Validation started.")

CustomFormatter

Bases: Formatter

Enhanced formatter for ImportSpy log messages.

Adds contextual metadata (file, line, function) to each log entry, improving traceability across CLI execution and embedded imports.

Format

"[timestamp] LEVEL logger name" "[caller: file, line, function] message"

Example

2025-08-07 14:30:12 INFO importspy.module caller: loader.py, line: 42, function: validate_import Validation passed.

__init__()

Initialize the formatter with ImportSpy's extended log format.

format(record)

Format the log record with caller information.

Adds custom attributes to the LogRecord for file name, line number, and function name.

Parameters:

Name Type Description Default
record LogRecord

The log record to format.

required

Returns:

Name Type Description
str str

Formatted log message string.

LogManager

Centralized manager for logging configuration in ImportSpy.

Ensures that all logs share a consistent format and output behavior, avoiding duplicate configuration across modules. Designed for both embedded validation flows and CLI analysis.

Attributes:

Name Type Description
default_level int

Default log level from the root logger.

default_handler StreamHandler

Stream handler with ImportSpy formatting.

configured bool

Whether the logger has already been initialized.

__init__()

Initialize the default logging handler and formatter.

configure(level=None, handlers=None)

Apply logging configuration globally.

Should be called once per execution to avoid duplicated handlers. Adds provided handlers or defaults to the built-in stream handler.

Parameters:

Name Type Description Default
level int

Logging level (e.g., logging.DEBUG). Defaults to current level.

None
handlers list[Handler]

Custom logging handlers.

None

Raises:

Type Description
RuntimeError

If configuration is attempted more than once.

get_logger(name)

Return a named logger configured with ImportSpy's formatter.

Ensures consistent behavior across all log invocations. If the logger does not yet have handlers, it assigns the default handler.

Parameters:

Name Type Description Default
name str

Name of the logger (typically a module or subpackage name).

required

Returns:

Type Description
Logger

logging.Logger: A logger instance ready for use.


importspy.utilities.module_util

Module utilities for runtime introspection and structure extraction.

This module provides utility functions for analyzing Python modules dynamically, primarily to support ImportSpy's runtime validation mechanisms. It enables inspection of modules, their metadata, and internal structure at runtime.

Features: - Inspect the call stack and determine caller modules. - Dynamically load and unload Python modules. - Extract version information via metadata or attributes. - Retrieve global variables, top-level functions, and class definitions. - Analyze methods, attributes (class-level and instance-level), and superclasses.

Example
from importspy.utilities.module_util import ModuleUtil
import inspect

module_util = ModuleUtil()
info = module_util.get_info_module(inspect.stack()[0])
print(info.__name__)

ModuleUtil

Provides methods to inspect and extract structural metadata from Python modules.

This class enables runtime inspection of loaded modules for metadata such as functions, classes, variables, inheritance hierarchies, and version information. It is a core component used by ImportSpy to validate structural contracts.

extract_annotation(annotation)

Convert a type annotation object into a string representation.

Parameters:

Name Type Description Default
annotation Any

The annotation object to convert.

required

Returns:

Type Description
Optional[str]

Optional[str]: The extracted annotation string or None.

extract_attributes(cls_obj, info_module)

Extract both class-level and instance-level attributes.

Parameters:

Name Type Description Default
cls_obj Any

The class to analyze.

required
info_module ModuleType

The module containing the class.

required

Returns:

Type Description
List[AttributeInfo]

List[AttributeInfo]: List of extracted attributes.

extract_classes(info_module)

Extract all class definitions from a module.

Parameters:

Name Type Description Default
info_module ModuleType

The module to inspect.

required

Returns:

Type Description
List[ClassInfo]

List[ClassInfo]: Metadata about the module’s classes.

extract_functions(info_module)

Extract all functions defined at the top level of the module.

Parameters:

Name Type Description Default
info_module ModuleType

The target module.

required

Returns:

Type Description
List[FunctionInfo]

List[FunctionInfo]: Function metadata extracted from the module.

extract_methods(cls_obj)

Extract method definitions from a class object.

Parameters:

Name Type Description Default
cls_obj Any

The class to inspect.

required

Returns:

Type Description
List[FunctionInfo]

List[FunctionInfo]: Extracted method metadata.

extract_superclasses(cls)

Extract base classes for a given class, recursively.

Parameters:

Name Type Description Default
cls Any

The class whose base classes are being extracted.

required

Returns:

Type Description
List[ClassInfo]

List[ClassInfo]: Metadata for each superclass.

extract_variables(info_module)

Extract top-level variable definitions from a module.

Parameters:

Name Type Description Default
info_module ModuleType

The module to analyze.

required

Returns:

Type Description
List[VariableInfo]

List[VariableInfo]: List of variable metadata.

extract_version(info_module)

Attempt to retrieve the version string from a module.

Parameters:

Name Type Description Default
info_module ModuleType

The target module.

required

Returns:

Type Description
str | None

str | None: Version string if found, otherwise None.

get_info_module(caller_frame)

Resolve a module object from a given caller frame.

Parameters:

Name Type Description Default
caller_frame FrameInfo

The caller frame to analyze.

required

Returns:

Type Description
ModuleType | None

ModuleType | None: The resolved module or None if not found.

inspect_module()

Retrieve the current and caller frames from the stack.

Returns:

Name Type Description
tuple tuple

A tuple with the current and the outermost caller frame.

load_module(info_module)

Reload a module dynamically from its file location.

Parameters:

Name Type Description Default
info_module ModuleType

The module to reload.

required

Returns:

Type Description
ModuleType | None

ModuleType | None: The reloaded module or None if loading fails.

unload_module(module)

Unload a module from sys.modules and globals.

Parameters:

Name Type Description Default
module ModuleType

The module to unload.

required

importspy.utilities.runtime_util

Runtime Environment Utilities

Provides a lightweight utility for querying the system's hardware architecture.

This module is used by ImportSpy to enforce architecture-specific constraints defined in import contracts (e.g., allowing a plugin only on x86_64 or arm64). It ensures that module imports are aligned with the intended deployment environment.

Example

from importspy.utilities.runtime_util import RuntimeUtil runtime = RuntimeUtil() runtime.extract_arch() 'x86_64'

RuntimeUtil

Utility class to inspect system architecture.

This class provides methods to retrieve runtime hardware architecture details, which are essential when validating platform-specific import constraints in ImportSpy's embedded or CLI modes.

extract_arch()

Return the name of the machine's hardware architecture.

Uses platform.machine() to retrieve the architecture string, which may vary depending on the underlying system (e.g., "x86_64", "arm64", "aarch64"). This is typically used during contract validation to ensure that the importing environment matches expected deployment conditions.

Returns:

Name Type Description
str str

The system's hardware architecture.

Example

RuntimeUtil().extract_arch() 'arm64'


importspy.utilities.system_util

System Utilities for ImportSpy

Provides tools to inspect the host operating system and environment variables.

This module supports ImportSpy by normalizing system-level information that may affect import contract validation. It helps ensure that environmental conditions are consistent and inspectable across different operating systems and deployment contexts.

Features
  • Detects the current operating system in a normalized, lowercase format.
  • Retrieves all environment variables as a list of structured objects.
Example

from importspy.utilities.system_util import SystemUtil util = SystemUtil() util.extract_os() 'linux' envs = util.extract_envs() envs[0] VariableInfo(name='PATH', annotation=None, value='/usr/bin')

SystemUtil

Utility class for inspecting system-level properties.

Used by ImportSpy to collect information about the current operating system and active environment variables. These details are typically validated against constraints defined in .yml import contracts.

Methods:

Name Description
extract_os

Return the normalized name of the current operating system.

extract_envs

Return all active environment variables as structured entries.

extract_envs()

Return all environment variables as a list of structured objects.

Collects all key-value pairs from os.environ and wraps them in VariableInfo namedtuples. The annotation field is reserved for optional type annotation metadata (currently set to None).

Returns:

Type Description
List[VariableInfo]

List[VariableInfo]: A list of environment variables available

List[VariableInfo]

in the current process environment.

Example

envs = SystemUtil().extract_envs() envs[0] VariableInfo(name='PATH', annotation=None, value='/usr/bin')

extract_os()

Return the name of the operating system in lowercase format.

This method uses platform.system() and normalizes the result to lowercase. It simplifies comparisons with import contract conditions that expect a canonical form such as "linux", "darwin", or "windows".

Returns:

Name Type Description
str str

The normalized operating system name (e.g., "linux", "windows").

Example

SystemUtil().extract_os() 'darwin'


importspy.utilities.python_util

Python Runtime Utilities

Provides utility methods to inspect the active Python runtime environment, such as the version number and interpreter implementation.

These utilities are useful within ImportSpy to evaluate whether the current runtime context satisfies declared compatibility constraints in import contracts. This includes checks for specific Python versions and interpreter families (CPython, PyPy, IronPython, etc.).

Example

from importspy.utilities.python_util import PythonUtil util = PythonUtil() util.extract_python_version() '3.12.0' util.extract_python_implementation() 'CPython'

PythonUtil

Utility class for inspecting Python runtime characteristics.

Used internally by ImportSpy to validate runtime-specific conditions declared in .yml import contracts. This includes checking Python version and interpreter type during structural introspection and contract validation.

extract_python_implementation()

Return the implementation name of the running Python interpreter.

Common values include "CPython", "PyPy", or "IronPython". This is essential in contexts where the implementation affects runtime behavior or compatibility with native extensions.

Returns:

Name Type Description
str str

The interpreter implementation (e.g., "CPython").

Example

PythonUtil().extract_python_implementation() 'CPython'

extract_python_version()

Return the currently active Python version as a string.

This method queries the runtime using platform.python_version() and is typically used to match version constraints defined in an import contract.

Returns:

Name Type Description
str str

The Python version string (e.g., "3.11.4").

Example

PythonUtil().extract_python_version() '3.11.4'