File imp.py of Package failed_python-pyeapi

"""
Compatibility shim for the deprecated 'imp' module removed in Python 3.12.

Some test suites (or legacy code) only import 'imp' to silence a deprecation
warning or to call a small subset of its API. Creating this shim allows code
that does "import imp" to continue working under Python 3.12+.

This shim provides a minimal, safe subset of functions that map to importlib.
It purposely avoids implementing the full (and removed) imp semantics — only
the common helpers that may be used by older code/tests are provided.

If your code requires more of 'imp' behavior, extend this shim with the
specific functions needed.
"""

from __future__ import annotations

import importlib
import importlib.util
import importlib.machinery
import types
import sys
from typing import Optional, Any


def new_module(name: str) -> types.ModuleType:
    """Return a new empty module object with the given name."""
    return types.ModuleType(name)


def find_module(name: str, path: Optional[list[str]] = None) -> Any:
    """
    Minimal replacement for imp.find_module.

    Returns a loader object if the module can be found, otherwise raises ImportError.
    """
    spec = importlib.util.find_spec(name)
    if spec is None:
        raise ImportError(f"Module {name!r} not found")
    return spec.loader


def load_module(name: str, file: Any, filename: Optional[str] = None, details: Optional[Any] = None) -> types.ModuleType:
    """
    Minimal replacement for imp.load_module.

    Common usages:
    - imp.load_module(name, filename, ...) where filename is a path to a source file.

    This implementation:
    - If 'file' is a string, treat it as a filename and load the module from that path.
    - Otherwise, attempt to import the module by name.
    """
    # If file is a filename string, load from source file
    if isinstance(file, str):
        loader = importlib.machinery.SourceFileLoader(name, file)
        spec = importlib.util.spec_from_loader(name, loader)
        if spec is None:
            raise ImportError(f"Cannot create spec for {name!r} from {file!r}")
        module = importlib.util.module_from_spec(spec)
        # Execute the module in its namespace
        loader.exec_module(module)
        sys.modules[name] = module
        return module

    # Fallback: try importing by name
    try:
        return importlib.import_module(name)
    except Exception as exc:
        raise ImportError(f"Cannot load module {name!r}") from exc


# Provide a small set of attributes that some code might expect
__all__ = [
    "new_module",
    "find_module",
    "load_module",
]
openSUSE Build Service is sponsored by