AWS Lambda の Python 3.15 を Event Functions と Web Functions で試してみた

AWS Lambda の Python 3.15 を Event Functions と Web Functions で試してみた

Event Functions では Python 3.15 ランタイムが GA、Web Functions では public preview として提供が始まったので、それぞれで動作を確認しました。frozendict、sentinel などの新機能が使え、Web Functions では FastAPI も動きました。
2026.11.22

はじめに

2026年11月20日に、AWS Lambda に Python 3.15 のサポートが追加されました。

https://aws.amazon.com/about-aws/whats-new/2026/11/aws-lambda-python-315/

Lambda の Python 3.15 ランタイムは、2026年8月に public preview として提供されていました。

https://dev.classmethod.jp/articles/lambda-preview-python315-node26/

今回は Python 3.15 ランタイムを、Event Functions と、public preview として提供が始まった Web Functions で試した結果を紹介します。

検証環境

  • リージョン:東京(ap-northeast-1)
  • AWS CLI:2.42.1
  • Event Function のアーキテクチャ:x86_64
  • Event Function のメモリ:128 MB

Event Functions

関数の作成と実行

frozendict、sentinel、lazy import を使う関数を python3.15 ランタイムで作成しました。次のコードを lambda_function.py として保存しました。

import sys

# explicit lazy import: この時点では sqlite3 は読み込まれない
lazy import sqlite3

MISSING = sentinel("MISSING")

def lookup(config, key):
    value = config.get(key, MISSING)
    return "not set" if value is MISSING else value

def lambda_handler(event, context):
    result = {"sys.version": sys.version}

    # frozendict
    config = frozendict(region="ap-northeast-1", memory=128)
    result["frozendict"] = {
        "repr": repr(config),
        "hashable": isinstance(hash(config), int),
        "lookup_region": lookup(config, "region"),
        "lookup_timeout": lookup(config, "timeout"),
    }
    try:
        config["memory"] = 256
    except TypeError as e:
        result["frozendict"]["setitem_error"] = str(e)

    # sentinel
    result["sentinel"] = {
        "repr": repr(MISSING),
        "type": type(MISSING).__name__,
        "is_not_None": MISSING is not None,
    }

    # lazy import
    result["lazy_import"] = {
        "sqlite3_loaded_before_use": "sqlite3" in sys.modules,
    }
    result["lazy_import"]["sqlite_version"] = sqlite3.sqlite_version
    result["lazy_import"]["sqlite3_loaded_after_use"] = "sqlite3" in sys.modules

    return result

実行ロールを用意しました。

実行ロールの作成

信頼ポリシーを trust-policy.json として保存しました。

{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
aws iam create-role --role-name yattemita-py315-event --assume-role-policy-document file://trust-policy.json --query Role.RoleName
aws iam attach-role-policy --role-name yattemita-py315-event --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

単一ファイルを zip に固め、--runtime python3.15 を指定して関数を作成しました。

zip event.zip lambda_function.py
aws lambda create-function --function-name yattemita-py315-event --runtime python3.15 --handler lambda_function.lambda_handler --role arn:aws:iam::111122223333:role/yattemita-py315-event --zip-file fileb://event.zip --query '{FunctionName:FunctionName,Runtime:Runtime,Architectures:Architectures,State:State,PackageType:PackageType}'
{
    "FunctionName": "yattemita-py315-event",
    "Runtime": "python3.15",
    "Architectures": [
        "x86_64"
    ],
    "State": "Pending",
    "PackageType": "Zip"
}

作成直後の State は Pending なので、Active になるまで待ってから実行しました。

aws lambda wait function-active-v2 --function-name yattemita-py315-event
aws lambda invoke --function-name yattemita-py315-event --log-type Tail --cli-binary-format raw-in-base64-out --payload '{}' --query '{StatusCode:StatusCode,LogResult:LogResult}' response.json
cat response.json
{"sys.version": "3.15.2 (main, Oct 27 2026, 20:23:37) [GCC 11.5.0 20240719 (Red Hat 11.5.0-5)]", "frozendict": {"repr": "frozendict({'region': 'ap-northeast-1', 'memory': 128})", "hashable": true, "lookup_region": "ap-northeast-1", "lookup_timeout": "not set", "setitem_error": "'frozendict' object does not support item assignment"}, "sentinel": {"repr": "MISSING", "type": "sentinel", "is_not_None": true}, "lazy_import": {"sqlite3_loaded_before_use": false, "sqlite_version": "3.40.0", "sqlite3_loaded_after_use": true}}

sys.version から、関数が Python 3.15.2 で実行されたことが分かりました。

3.15 の新機能の確認

frozendict と sentinel は、import せずにそのまま使えました。frozendict の要素への代入は TypeError になり、hash() は整数を返しました。sentinel で作った MISSING は、config.get の既定値として使えました。

lazy import した sqlite3 は、使う前は sys.modules になく、sqlite3.sqlite_version を参照した後で含まれるようになりました。

lazy import の Init Duration

測定方法

lazy import したモジュールは、使うまで読み込まれません。同じ 16 個の標準ライブラリのモジュールを、通常の import で読み込む関数(eager 版)と lazy import で読み込む関数(lazy 版)を作り、Init Duration を比べました。ハンドラはどのモジュールも使わず、16 個のうち sys.modules にある数を返すだけです。

作成手順は前節と同じで、関数名は yattemita-py315-lazy と yattemita-py315-eager です。環境変数を更新してコールドスタートを起こし、REPORT 行の Init Duration を 10 回ずつ測定しました。

lazy 版のコードと作成コマンド

lambda_function.py(lazy 版):

import sys

lazy import asyncio
lazy import ssl
lazy import sqlite3
lazy import decimal
lazy import http.client
lazy import email.mime.text
lazy import xml.dom.minidom
lazy import unittest
lazy import zipfile
lazy import tarfile
lazy import argparse
lazy import csv
lazy import multiprocessing
lazy import concurrent.futures
lazy import urllib.request
lazy import pydoc

MODULES = "asyncio ssl sqlite3 decimal http.client email.mime.text xml.dom.minidom unittest zipfile tarfile argparse csv multiprocessing concurrent.futures urllib.request pydoc".split()

def lambda_handler(event, context):
    loaded = [m for m in MODULES if m in sys.modules]
    return {"mode": "lazy", "listed": len(MODULES), "loaded_at_handler": len(loaded)}
zip lazy.zip lambda_function.py
aws lambda create-function --function-name yattemita-py315-lazy --runtime python3.15 --handler lambda_function.lambda_handler --role arn:aws:iam::111122223333:role/yattemita-py315-event --zip-file fileb://lazy.zip --query '{FunctionName:FunctionName,Runtime:Runtime,Architectures:Architectures,MemorySize:MemorySize}'

eager 版は、各 import 文の lazy を外し、返す辞書の "mode" を "eager" にした以外は同じコードです。作成コマンドでは、関数名と zip ファイル名の lazy を eager に置き換えました。

測定スクリプト

measure-init.sh として保存し、bash measure-init.sh <関数名> 10 で実行しました。

#!/bin/bash
# 環境変数を変えて強制的にコールドスタートさせ、REPORT 行を取り出す
# usage: measure-init.sh <function-name> <回数>
set -euo pipefail
fn=$1; n=$2
for i in $(seq 1 "$n"); do
  aws lambda update-function-configuration --function-name "$fn" \
    --environment "Variables={ROUND=$i-$(date +%s)}" --query LastUpdateStatus --output text >/dev/null
  aws lambda wait function-updated-v2 --function-name "$fn"
  aws lambda invoke --function-name "$fn" --log-type Tail --payload '{}' \
    --cli-binary-format raw-in-base64-out --query LogResult --output text /tmp/out-$fn.json \
    | base64 -d | grep REPORT | sed "s/^/$fn run$i: /"
done

測定結果

表の値は、10 回のコールドスタートで測った Init Duration の集計です(単位は ms、x86_64、128 MB)。lazy 版と eager 版の測定ループは並行して実行しました。

版 中央値 平均 最小 最大
lazy 版 118.0 115.5 92.8 139.1
eager 版 259.0 295.9 216.1 538.7

eager 版で最も速かった回(216.08 ms)でも、lazy 版で最も遅かった回(139.06 ms)より遅い結果でした。

ハンドラの戻り値 loaded_at_handler は、eager 版が 16、lazy 版が 2 でした。lazy 版で読み込まれていた 2 個は decimal と concurrent.futures で、何も import しない関数でもハンドラ実行時には読み込まれていました。表の差は、残りの 14 個が遅延された結果です。

Web Functions

標準ライブラリだけの ASGI アプリ

Web Function では、main.py に app という名前で ASGI アプリを定義しました。標準ライブラリだけで書いたアプリを web-min/main.py として保存しました。frozendict が Web Function でも使えるか確かめるため、応答にその repr を含めています。

import json
import sys

async def app(scope, receive, send):
    if scope["type"] != "http":
        return
    body = json.dumps({
        "message": "Hello from Lambda Web Functions",
        "sys.version": sys.version,
        "method": scope["method"],
        "path": scope["path"],
        "frozendict": repr(frozendict(path=scope["path"])),
    }).encode()
    await send({
        "type": "http.response.start",
        "status": 200,
        "headers": [(b"content-type", b"application/json")],
    })
    await send({"type": "http.response.body", "body": body})

aws lambda-web deploy の --code にディレクトリ、--runtime に python を指定してデプロイしました。

aws lambda-web deploy --name yattemita-py315-web --code web-min --runtime python --create
Creating deployment package ...
Preparing Amazon S3 bucket ...
Preparing AWS IAM execution role ...
Uploading deployment package ...
Creating Lambda Web Function ...
Waiting for endpoint to become active (timeout 600s) ...
Waiting for endpoint to become active (state Pending, 0s elapsed, timeout 600s) ...
Waiting for endpoint to become active (state Pending, 5s elapsed, timeout 600s) ...
https://<ID>.r8m.lambda-web.ap-northeast-1.on.aws

--runtime python を指定すると、リビジョンの runtimeConfig は python3.15 になりました。aws lambda-web get-web-function-revision で確認しました。

"runtimeConfig": {
    "runtime": "python3.15"
}

出力されたエンドポイントに curl でリクエストを送りました。

curl -sS -i -m 60 'https://<ID>.r8m.lambda-web.ap-northeast-1.on.aws/hello?x=1'
HTTP/1.1 200 OK
Server: uvicorn
Date: Sat, 21 Nov 2026 15:34:41 GMT
date: Sat, 21 Nov 2026 15:34:41 GMT
Content-Type: application/json
lambda-web-logstream: 2026/11/21/yattemita-py315-web[rev-rpuuo]<ID>
Transfer-Encoding: chunked
lambda-web-request-id: SMEGUYQFBBW2YWE3SUOHQDRVB4

{"message": "Hello from Lambda Web Functions", "sys.version": "3.15.2 (main, Nov 12 2026, 21:19:02) [GCC 11.5.0 20240719 (Red Hat 11.5.0-5)]", "method": "GET", "path": "/hello", "frozendict": "frozendict({'path': '/hello'})"}

CloudWatch Logs のロググループ /aws/lambda/web/yattemita-py315-web には、次の警告が出力されていました。

LAMBDA_WARNING: This is a preview runtime version and should not be used for production workloads. For further information and to provide feedback, see https://docs.aws.amazon.com/lambda/latest/dg/web-functions-runtimes.html

Event Function の実行ログには、この警告は出ませんでした。

FastAPI アプリ

deploy のヘルプには、Web Functions は arm64 で動き、deploy は依存をインストールしないと書かれています。uv pip install で arm64 向けにインストールする例も載っています。その例では --python-platform aarch64-manylinux_2_34 --python-version 3.15 を付けます。ここでは Docker の python:3.15 イメージで、arm64 向けの cp315 wheel をプロジェクトのディレクトリへインストールしました。

web-fastapi/requirements.txt には 1 行だけ書きました。

fastapi
docker run --rm --user "$(id -u):$(id -g)" -e HOME=/tmp -v "$(pwd)/web-fastapi:/app" -w /app python:3.15 pip install -r requirements.txt --target . --only-binary=:all: --python-version 3.15 --platform manylinux2014_aarch64 --platform manylinux_2_28_aarch64 --platform manylinux_2_34_aarch64
Downloading pydantic_core-2.50.5-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl (2.1 MB)
...
Successfully installed annotated-doc-0.0.7 annotated-types-0.8.0 anyio-4.16.0 fastapi-0.165.0 idna-3.20 opentelemetry-api-1.45.2 pydantic-2.14.4 pydantic-core-2.50.5 starlette-1.10.0 typing-extensions-4.16.0 typing-inspection-0.4.5

pydantic-core には cp315 の arm64 wheel があり、ソースからビルドせずにインストールできました。アプリは web-fastapi/main.py に書きました。

import sys

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello-world")
async def hello_world():
    return {
        "message": "Hello from Lambda Web Functions",
        "sys.version": sys.version,
        "frozendict": repr(frozendict(framework="fastapi")),
    }

デプロイは前節と同じ形で、--code に依存パッケージをインストールしたディレクトリを指定しました。

aws lambda-web deploy --name yattemita-py315-fastapi --code web-fastapi --runtime python --create
curl -sS -i -m 60 https://<ID>.r8m.lambda-web.ap-northeast-1.on.aws/hello-world
HTTP/1.1 200 OK
Server: uvicorn
Date: Sat, 21 Nov 2026 15:35:38 GMT
date: Sat, 21 Nov 2026 15:35:38 GMT
Content-Type: application/json
Content-Length: 191
lambda-web-logstream: 2026/11/21/yattemita-py315-fastapi[rev-kxmgs]<ID>
lambda-web-request-id: 7TZPR5T33Z2ILBHQNBPEMRY3VE

{"message":"Hello from Lambda Web Functions","sys.version":"3.15.2 (main, Nov 12 2026, 21:19:02) [GCC 11.5.0 20240719 (Red Hat 11.5.0-5)]","frozendict":"frozendict({'framework': 'fastapi'})"}

--entry-point と環境変数 AWS_LAMBDA_PYTHON_ENTRYPOINT は指定せず、既定の main:app のままで FastAPI が動きました。

まとめ

Lambda の Event Functions では GA、Web Functions では public preview として提供が始まった Python 3.15 ランタイムで、frozendict、sentinel、lazy import などの動作を確認できました。

また、これまで Node.js 専用だった Web Functions で Python が使えるようになり、標準ライブラリだけの ASGI アプリと FastAPI が動きました。

Web Functions で Node.js 以外を使いたい方は、Python 3.15 ランタイムをお試しください。

この記事をシェアする

AWSのお困り事はクラスメソッドへ

関連記事