Skip to content

Python API reference

The 0.5 API separates source inspection, evidence collection, policy evaluation, and explicit execution. Start with library admission and architecture; use extensions for third-party providers, validators, and reporters.

Admission engine

AdmissionEngine.check(AdmissionRequest(...)) returns an AdmissionDecision without target execution. load performs fresh admission and explicitly executes captured source bytes. AdmissionDenied and ExecutionFailed retain their associated decision.

Admission orchestration and the separate explicit execution boundary.

AdmissionEngine

check(request)

Inspect and decide without executing target code, whether admitted or denied.

load(request, *, name=None)

Freshly admit, execute the inspected bytes once, then validate runtime objects.

This executes arbitrary Python. It is not a sandbox. Runtime checks happen after top-level effects and must never be described as static preflight.

Requests, facts, and decisions

The shared domain records serialize to JSON through Pydantic's model_dump(mode="json") and model_dump_json() methods. Decision schema version and contract schema version describe separate record formats.

Serializable admission facts and decisions shared by the engine and extensions.

Contracts and policy

AdmissionPolicy extends the structural model. load_policy uses safe YAML and returns the validated policy with its SHA-256 hash. PolicyEngine.evaluate compares collected facts without performing I/O.

Validated contract schema and pure evidence policy evaluation.

AdmissionPolicy

Bases: SpyModel

0.5 extends SpyModel's structural fields; version remains module version.

ContractError

Bases: ValueError

The policy cannot be interpreted; callers should use exit code 2.

PolicyEngine

Evaluate already collected facts. No filesystem, imports or network operations.

collect_runtime_evidence(policy, context)

Inspect host facts only; environment values are never serialized.

Static source inspection

SourceInspector.inspect reads, hashes, parses, and compiles source without execution. evaluate_structure compares structural requirements with those facts; starter_contract generates editable structural requirements.

Inspect Python declarations without importing, evaluating, or executing source.

Facts describe source declarations, not guarantees about the resulting runtime objects. Unknown facts remain explicit and cannot satisfy structural requirements.

SourceInspector

Collect AST facts from a file without executing it or its dependencies.

evaluate_structure(expected, inspection)

Compare contract requirements to static facts; unknowns fail closed.

Inspection failures are available separately in inspection.violations. This function does not mutate inspection evidence or perform any I/O.

starter_contract(inspection)

Generate an editable structural contract; never turn unknowns into approvals.

Only names are generated for signatures because the legacy annotation/value DSL cannot represent every Python signature. Decorated and conditional declarations remain requirements and therefore fail closed until reviewed.

Dependency resolution

DependencyResolver uses source paths and installed metadata without importing the target dependencies. An instance is a metadata snapshot; recreate it after changing installations. Origin and declaration facts retain unknown states.

Metadata-only dependency resolution and deterministic dependency policy.

DependencyResolver

Resolve using source paths and installed metadata, never target imports.

Each instance is a metadata snapshot: reuse for a batch, recreate after installs. Custom metadata finders already installed in the host are part of its trust boundary.

evaluate_dependencies(deps, rules, options, subject)

Evaluate collected facts without IO. Provenance uses the evidence policy layer.

normalize_url(value, *, repository=False)

Normalize an origin URL while removing userinfo, query and fragment.

read_origin(raw)

Read untrusted PEP 610 metadata; missing or malformed data stays unknown.

Extension protocols

Provider loading is explicit and executes trusted plugin code. RuntimeValidator here is the post-execution protocol; it is distinct from the legacy class with the same name in importspy.validators.

Small explicit extension boundaries. Loading a plugin executes trusted plugin code.

RuntimeValidator

Bases: Protocol

Runs only after explicit, admitted module execution; cannot undo side effects.

load_provider(name)

Load exactly one user-selected entry point, never all installed providers.

Reporters

Human, JSON, and SARIF reporters render the same decision. A reporter does not collect evidence or evaluate policy again.

Human, JSON and SARIF views of the same admission decision.

Legacy runtime compatibility

These modules support 0.4-style validation of already executed modules. Spy.importspy is deprecated in 0.5, with removal planned for 1.0. SpyModel.from_module is runtime introspection and can invoke dynamic attributes; it is not static admission. See migration.

Compatibility API for validating modules that have already executed.

Use AdmissionEngine for static admission before execution. The deprecated Spy API performs runtime introspection and cannot provide that guarantee.

Spy

Legacy runtime validation for already loaded modules.

importspy remains available throughout 0.5 and is scheduled for removal in 1.0. Runtime introspection can invoke dynamic Python attributes and must only be used with trusted, already admitted modules.

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

Validate and return the same already loaded module without reloading.

Deprecated since 0.5; use AdmissionEngine.check for pre-execution admission. If info_module is omitted, inspect the caller's module. A contract file is required. Validation failures raise ValueError.

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

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: ContractModel

Represents a Python class declaration.

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

ContractModel

Bases: BaseModel

Reject unrecognized contract fields instead of silently ignoring policy typos.

Environment

Bases: ContractModel

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

Error

Bases: ContractModel

Describes a structured validation error.

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

Function

Bases: ContractModel

Represents a callable entity.

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

Module

Bases: ContractModel

Represents a Python module.

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

Python

Bases: ContractModel

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: ContractModel

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 already loaded Python module object, without reloading or unregistering it. This is runtime introspection, not static admission: the caller has already executed the module and dynamic attributes may run Python code during inspection.

System

Bases: ContractModel

Represents a full OS environment within a deployment system.

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

Variable

Bases: ContractModel

Represents a top-level variable in a Python module.

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

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.

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 Sequence[Class] | None

Expected class definitions.

required
classes_2 Sequence[Class] | None

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 Sequence[Function] | None

Expected functions.

required
functions_2 Sequence[Function] | None

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 Sequence[Module] | None

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 Sequence[Python] | None

Contract-defined expectations.

required
pythons_2 Sequence[Python] | None

Runtime-detected Python instances.

required
contract_violation PythonContractViolation

Context bundle and error factory.

required

Returns:

Type Description
List[Module] | 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 Sequence[Runtime] | None

Declared runtime requirements.

required
runtimes_2 Sequence[Runtime] | None

Observed runtime environments.

required
contract_violation RuntimeContractViolation

Violation reporter instance.

required

Returns:

Name Type Description
Runtime 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 | None

Expected environment.

required
environment_2 Environment | None

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 Sequence[System] | None

Expected system definitions.

required
systems_2 Sequence[System] | None

Runtime-observed systems.

required
contract_violation SystemContractViolation

Violation context and bundle.

required

Returns:

Type Description
List[Python] | 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 Sequence[Variable] | None

Expected variables.

required
variables_2 Sequence[Variable] | None

Actual runtime variables.

required
contract_violation VariableContractViolation

Violation and error builder.

required

Raises:

Type Description
ValueError

On missing or mismatched variables.

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[str, Any]

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.

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:
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:
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:
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. Uses the safe YAML constructor; Python objects and custom tags are rejected.

__init__()

Initializes the YAML parser and configures output formatting.

load(filepath)

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

Parameters:
str

Path to the contract file.

Returns:

dict Parsed contract structure.

save(data, filepath)

Saves a contract dictionary to a .yml file.

Parameters:
dict

Contract structure.

str

Destination file path.

handle_persistence_error(func)

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

Catches ordinary 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.