Skip to content

ctx

A simple hashmap for working with types in a contextual manner.

TypeContext

Bases: dict[KeyT, ValueT], Generic[ValueT]

A key-value mapping which can map between forward references and real types.

__missing__

__missing__(key: type | ForwardRef)

Hook to handle missing type references.

Allows for sharing lookup results between forward references, type aliases, real types.

Parameters:

  • key (type | ForwardRef) –

    The type or reference.

Source code in src/typelib/ctx.py
def __missing__(self, key: type | refs.ForwardRef):
    """Hook to handle missing type references.

    Allows for sharing lookup results between forward references, type aliases, real types.

    Args:
        key: The type or reference.
    """
    # If we missed a ForwardRef, we've already tried this, bail out.
    if isinstance(key, refs.ForwardRef):
        raise KeyError(key)

    unwrapped = inspection.unwrap(key)
    if unwrapped in self:
        val = self[unwrapped]
        # Store the value at the original key to short-circuit in future
        self[key] = val
        return val

    ref = refs.forwardref(key)
    return self[ref]