cocoindex-io/cocoindex · error · Error

Unexpected error importing module '{app_target}': {e}

Error message

Unexpected error importing module '{app_target}': {e}

What it means

While importing the app target as a module, an exception other than ImportError escaped importlib.import_module (e.g. SyntaxError, AttributeError, TypeError raised at module top level). CocoIndex labels it 'Unexpected error' to distinguish genuine code failures from import-resolution failures, and wraps it in Error.

Source

Thrown at python/cocoindex/user_app_loader.py:108

    # If the target looks like a bare module name (e.g. "main") and a
    # corresponding file exists in the CWD inside a package, load via the
    # package-qualified name so relative imports work.
    candidate_file = os.path.join(os.getcwd(), app_target + ".py")
    cwd = os.getcwd()
    if os.path.isfile(candidate_file) and os.path.isfile(
        os.path.join(cwd, "__init__.py")
    ):
        root_parent, package_parts = _find_package_root(cwd)
        return _import_as_package_module(root_parent, package_parts, app_target)

    # Try as module
    try:
        return importlib.import_module(app_target)
    except ImportError as e:
        raise Error(f"Failed to load module '{app_target}': {e}") from e
    except Exception as e:
        raise Error(f"Unexpected error importing module '{app_target}': {e}") from e

View on GitHub (pinned to e84aa99b32)

Solutions

  1. Read the wrapped exception message and fix the bug at the reported line in the app module.
  2. Run `python -c "import <module>"` (or `python <file>.py`) directly to see the full traceback.
  3. Check Python version compatibility (`python --version`) if the error involves new syntax.
  4. Move heavy top-level side effects (network/DB) inside functions so import succeeds.

Example fix

# before (app.py)
DB = connect(os.environ["DB_URL"])  # KeyError at import

# after
def get_db():
    return connect(os.environ["DB_URL"])
Defensive patterns

Strategy: try-catch

Validate before calling

// smoke-test import first
// python -c "import main"

Try / catch

try:
    load_user_app(target)
except Error as e:
    print(e)  # message includes the original non-ImportError exception
    raise SystemExit(1)

Prevention

When it happens

Trigger: importlib.import_module(app_target) executes the module's top-level code and that code raises any non-ImportError exception: SyntaxError in the app file, a NameError/TypeError during initialization, or an unrelated exception from an imported library.

Common situations: Recently edited app file with a syntax error; top-level code that reads env vars or connects to a database and fails; Python version mismatch causing TypeError on new syntax (e.g. match statements on old interpreters).

Related errors


AI-assisted analysis of cocoindex-io/cocoindex@e84aa99b32 (2026-09-08). Data as JSON: /api/errors/ef7d5a01d73e30e1. Report an issue: GitHub.