Skip to content

Models

Common data models used across Lambda handlers.


Data models for Lambda handler configuration and execution.

Provides models for Lambda context, handler requests, and serialization utilities.

DefaultLambdaContext dataclass

DefaultLambdaContext(
    _function_name=(
        lambda: get_env_var(AWS_LAMBDA_FUNCTION_NAME_KEY)
        or DEFAULT_AWS_LAMBDA_FUNCTION_NAME
    )(),
    _function_version=(
        lambda: get_env_var(
            AWS_LAMBDA_FUNCTION_VERSION_KEY,
            default_value="1.0",
        )
    )(),
    _invoked_function_arn=(
        lambda: get_env_var(
            AWS_LAMBDA_FUNCTION_ARN_KEY, default_value=""
        )
    )(),
    _memory_limit_in_mb=(
        lambda: int(
            get_env_var(
                AWS_LAMBDA_FUNCTION_MEMORY_SIZE_KEY,
                default_value="1024",
            )
        )
    )(),
    _aws_request_id=(
        lambda: get_env_var(
            AWS_LAMBDA_FUNCTION_REQUEST_ID_KEY,
            default_value="",
        )
    )(),
    _log_group_name=(
        lambda: get_env_var(
            AWS_LAMBDA_LOG_GROUP_NAME_KEY, default_value=""
        )
    )(),
    _log_stream_name=(
        lambda: get_env_var(
            AWS_LAMBDA_LOG_STREAM_NAME_KEY, default_value=""
        )
    )(),
    _identity=(lambda: LambdaCognitoIdentity())(),
    _client_context=(lambda: LambdaClientContext())(),
)

Bases: LambdaContext

Standard implementation of LambdaContext for non-Lambda environments.

Provides a mock Lambda context for running handlers outside of AWS Lambda, such as in Docker containers or for local testing. All fields can be configured via environment variables.

LambdaHandlerRequest

Bases: PydanticBaseModel

Request model for dynamic Lambda handler invocation.

Contains the handler reference and event payload for routing Lambda invocations to the appropriate handler.

Attributes:

Name Type Description
handler Annotated[LambdaHandlerType, BeforeValidator(deserialize_handler), PlainSerializer(lambda handler: serialize_handler(handler))]

The Lambda handler function to invoke.

event LambdaEvent

The event payload to pass to the handler.

deserialize_handler

deserialize_handler(handler)

Deserialize a handler from its qualified name.

Loads a handler from its fully qualified module path. Supports both function handlers and LambdaHandler subclasses.

Parameters:

Name Type Description Default
handler str

The fully qualified handler path (e.g., 'module.submodule.HandlerClass').

required

Returns:

Type Description
LambdaHandlerType

The Lambda handler function ready to be invoked.

Raises:

Type Description
ValueError

If the handler cannot be deserialized or is not a valid handler type.

Example
handler = deserialize_handler('my_module.MyHandler')
response = handler(event, context)
Source code in src/aibs_informatics_aws_lambda/common/models.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def deserialize_handler(handler: str | LambdaHandlerType) -> LambdaHandlerType:
    """Deserialize a handler from its qualified name.

    Loads a handler from its fully qualified module path. Supports both
    function handlers and LambdaHandler subclasses.

    Args:
        handler (str): The fully qualified handler path (e.g., 'module.submodule.HandlerClass').

    Returns:
        The Lambda handler function ready to be invoked.

    Raises:
        ValueError: If the handler cannot be deserialized or is not a valid handler type.

    Example:
        ```python
        handler = deserialize_handler('my_module.MyHandler')
        response = handler(event, context)
        ```
    """
    if not isinstance(handler, str):
        if not callable(handler):
            raise ValueError(
                f"Invalid handler type: expected a callable or fully qualified handler path "
                f"string, got {type(handler).__name__}."
            )
        return cast(LambdaHandlerType, handler)
    handler_components = handler.split(".")

    handler_module = as_module_type(".".join(handler_components[:-1]))
    handler_name = handler_components[-1]

    handler_code = getattr(handler_module, handler_name)
    if inspect.isfunction(handler_code):
        return cast(LambdaHandlerType, handler_code)
    elif inspect.isclass(handler_code) and issubclass(handler_code, LambdaHandler):
        logger.debug(f"Handler code is a class: {handler_code}. Calling `get_handler`...")
        return handler_code.get_handler()
    else:
        raise ValueError(
            f"Unable to deserialize handler: {handler}. "
            "It is not a function or a subclass of LambdaHandler."
        )

serialize_handler

serialize_handler(handler)

Serialize a Lambda handler to its qualified name.

For closures (e.g., from LambdaHandler.get_handler()), the function's __qualname__ points to the closure definition site rather than the module-level variable that holds it. This searches sys.modules for a global variable that references the exact handler object, so that constructor arguments passed to get_handler() are preserved on round-trip.

Parameters:

Name Type Description Default
handler LambdaHandlerType

The Lambda handler function or class.

required

Returns:

Type Description
str

The fully qualified module path of the handler.

Source code in src/aibs_informatics_aws_lambda/common/models.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def serialize_handler(handler: LambdaHandlerType) -> str:
    """Serialize a Lambda handler to its qualified name.

    For closures (e.g., from ``LambdaHandler.get_handler()``), the function's
    ``__qualname__`` points to the closure definition site rather than the
    module-level variable that holds it. This searches ``sys.modules`` for a
    global variable that references the exact handler object, so that
    constructor arguments passed to ``get_handler()`` are preserved on
    round-trip.

    Args:
        handler (LambdaHandlerType): The Lambda handler function or class.

    Returns:
        The fully qualified module path of the handler.
    """
    # For closures, try to find a module-level variable referencing this handler
    if "<locals>" in getattr(handler, "__qualname__", ""):
        import sys

        for module_name, module in sys.modules.items():
            if module is None:
                continue
            try:
                module_dict = vars(module)
            except TypeError:
                continue
            for attr_name, attr_value in module_dict.items():
                if attr_value is handler:
                    return f"{module_name}.{attr_name}"
        # Fall back to the originating class if the variable wasn't found
        handler_class = getattr(handler, "_handler_class", None)
        if handler_class is not None:
            return get_qualified_name(handler_class)
    return get_qualified_name(handler)