cocoindex-io/cocoindex · error · TypeError

expected {tp.__name__}{loc}, got {type(value).__name__}: {va

Error message

expected {tp.__name__}{loc}, got {type(value).__name__}: {value!r}

What it means

For simple concrete types (str, int, bytes, uuid.UUID, etc.), the TypeChecker builds check_isinstance, which raises this TypeError when the value is not an instance of the declared class. Unlike the tuple errors, the message includes the offending value itself (repr) to ease debugging. This is the library's leaf-level type enforcement for scalar fields.

Source

Thrown at python/cocoindex/_internal/datatype.py:387

                    fn(elem, f"{path}[{i}]")

            return check_fixed_tuple

        # Bare tuple (no args) — just check isinstance
        def check_bare_tuple(value: Any, path: str) -> None:
            if not isinstance(value, tuple):
                loc = f" at {path}" if path else ""
                raise TypeError(f"expected tuple{loc}, got {type(value).__name__}")

        return check_bare_tuple

    # Simple concrete type: str, int, bytes, uuid.UUID, etc.
    if isinstance(tp, type):

        def check_isinstance(value: Any, path: str) -> None:
            if not isinstance(value, tp):
                loc = f" at {path}" if path else ""
                raise TypeError(
                    f"expected {tp.__name__}{loc}, got {type(value).__name__}: {value!r}"
                )

        return check_isinstance

    raise ValueError(f"Unsupported type for TypeChecker: {tp}")


T = TypeVar("T")


class TypeChecker(Generic[T]):
    """
    Pre-built runtime type checker.

    Analyzes a type annotation once at construction time and builds optimized
    validation closures.  At check time, validation is a fast series of
    ``isinstance`` calls and tuple-length comparisons — no reflection.

View on GitHub (pinned to e84aa99b32)

Solutions

  1. Convert the value before passing: int(s), uuid.UUID(s), str(b, 'utf-8')
  2. If it is a NumPy/torch scalar, convert with .item() so it becomes a builtin type
  3. Correct the declared type annotation if the wrong type was declared

Example fix

// before
check(doc_id)  # doc_id = "550e8400-e29b-41d4-...", declared uuid.UUID
// after
import uuid
doc_id = uuid.UUID("550e8400-e29b-41d4-a716-446655440000")
check(doc_id)
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(value, tp):
    raise TypeError(f"{name!r} must be {tp.__name__}, got {type(value).__name__}: {value!r}")

Type guard

def is_instance_of(value: object, tp: type) -> TypeGuard[Any]:
    return isinstance(value, tp)

Try / catch

try:
    check(value)
except TypeError as e:
    log.error("field type mismatch: %s", e)
    raise

Prevention

When it happens

Trigger: Passing a value of the wrong concrete type where a scalar type is declared — e.g. a str where int is declared, bytes where str is declared, or an int where uuid.UUID is declared — in @coco.fn arguments, target-state fields, or TypeChecker.check().

Common situations: Passing numeric strings from config/CLI/env into int fields; passing raw UUID strings where uuid.UUID is declared; NumPy scalar types (np.int64) where Python int is declared and isinstance fails; bool where int is expected or vice versa.

Understand the failure class

Background: Type mismatch errors: IllegalArgumentException, TypeError and type guards across 150 open-source libraries — this error's family across 150 libraries.

Related errors


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