cocoindex-io/cocoindex · error · TypeError

Context key '{key}': expected {t.__name__}, got {type(value)

Error message

Context key '{key}': expected {t.__name__}, got {type(value).__name__}

What it means

ContextProvider.get accepts an optional type parameter `t`; when given a string key plus a type, it verifies the retrieved value is an instance of that type at runtime and raises TypeError on mismatch. This catches provider/consumer type disagreements early.

Source

Thrown at python/cocoindex/_internal/context_keys.py:265

    @overload
    def get(self, key: ContextKey[T]) -> T: ...
    @overload
    def get(self, key: str) -> Any: ...
    @overload
    def get(self, key: str, t: type[T]) -> T: ...
    def get(self, key: ContextKey[T] | str, t: type[T] | None = None) -> Any:
        """Get a value from the context. Raises KeyError if not found.

        Overloads:
          get(key: ContextKey[T]) -> T
          get(key: str) -> Any
          get(key: str, t: type[T]) -> T  — also verifies the type at runtime
        """
        if isinstance(key, str):
            value = self._values[key]
            if t is not None and not isinstance(value, t):
                raise TypeError(
                    f"Context key '{key}': expected {t.__name__}, got {type(value).__name__}"
                )
            return value
        return cast(T, self._values[key._key])

    async def aclose(self) -> None:
        await self._exit_stack.aclose()

View on GitHub (pinned to e84aa99b32)

Solutions

  1. Make the requested type match what was actually provided, or cast/coerce the value after retrieval
  2. Retrieve via the typed ContextKey[T] object instead of the string+type form so types are checked at the provider boundary
  3. Fix the provide() call site to store the correct type

Example fix

// before
pool = ctx.get("db", str)  # stored value is a Pool

// after
pool = ctx.get(DB_KEY)  # typed ContextKey[asyncpg.Pool]
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(ctx._values.get("db_key"), MyType):
    raise TypeError("context value has wrong type before get()")

Type guard

def is_pool(v: object) -> TypeGuard[asyncpg.Pool]:
    return isinstance(v, asyncpg.Pool)

Try / catch

try:
    pool = ctx.get("db", asyncpg.Pool)
except TypeError as e:
    logging.error("context type mismatch: %s", e)
    pool = build_pool_fallback()

Prevention

When it happens

Trigger: Calling provider.get("some_key", MyType) (string form) where the value stored under that key was provided with a different Python type — e.g. provided an asyncpg.Pool but requested str, or provided a Path but requested str.

Common situations: Key string collides across providers storing different types; refactoring changed the provided type but not the consumer's declared type; passing a subclass-expected type where value is a duck-typed lookalike (isinstance check fails).

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/0a9ed40a141e7243. Report an issue: GitHub.