A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: python 3.13 support (#4193)
Myles Scolnicke099459bbeb8
diff --git a/.github/workflows/test_be.yaml b/.github/workflows/test_be.yamlindex 2c7ccab525..88eaaea606 100644--- a/.github/workflows/test_be.yaml+++ b/.github/workflows/test_be.yaml@@ -70,6 +70,9 @@ jobs:- os: ubuntu-latestpython-version: '3.12'dependencies: 'core'+ - os: ubuntu-latest+ python-version: '3.13'+ dependencies: 'core'- os: ubuntu-latestpython-version: '3.9'dependencies: 'core,optional'@@ -82,6 +85,9 @@ jobs:- os: ubuntu-latestpython-version: '3.12'dependencies: 'core,optional'+ - os: ubuntu-latest+ python-version: '3.13'+ dependencies: 'core,optional'steps:- name: 🛑 Cancel Previous Runsuses: styfle/[email protected]diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.pyindex 770e185ba5..0569b678b5 100644--- a/marimo/_output/formatters/df_formatters.py+++ b/marimo/_output/formatters/df_formatters.py@@ -65,7 +65,7 @@ class PyArrowFormatter(FormatterFactory):return "pyarrow"def register(self) -> None:- import pyarrow as pa+ import pyarrow as pa # type: ignore[import-not-found]from marimo._output import formattingdiff --git a/marimo/_server/api/middleware.py b/marimo/_server/api/middleware.pyindex a1ea462e60..6ce1e85d81 100644--- a/marimo/_server/api/middleware.py+++ b/marimo/_server/api/middleware.py@@ -216,11 +216,12 @@ class _AsyncHTTPResponse:class _AsyncHTTPClient:- def __init__(self, base_url: str):+ def __init__(self, base_url: str, timeout: float = 30.0):self.base_url = base_url.rstrip("/")parsed = urlparse(base_url)self.host = parsed.netlocself.is_https = parsed.scheme == "https"+ self.timeout = timeoutdef build_request(self, method: str, url: Any, headers: dict[str, str], content: Any@@ -243,70 +244,88 @@ class _AsyncHTTPClient:request.method = methodreturn request- async def send(- self, request: _URLRequest, stream: bool = False- ) -> _AsyncHTTPResponse:- del stream- loop = asyncio.get_event_loop()-- async def collect_body() -> bytes:- if hasattr(request, "data"):- if request.data is None:- return b""- if isinstance(request.data, AsyncIterable):- chunks: list[bytes] = []- try:- async for chunk in request.data:- if isinstance(chunk, str):- chunks.append(chunk.encode())- else:- chunks.append(chunk)- return b"".join(chunks)- except Exception:- raise- if isinstance(request.data, str):- return request.data.encode()- if isinstance(request.data, bytes):- return request.data- if hasattr(request.data, "read"):- return request.data.read() # type: ignore- raise ValueError(- f"Unsupported request data type: {type(request.data)}"- )+ async def _collect_body(self, request: _URLRequest) -> bytes:+ if not hasattr(request, "data") or request.data is None:return b""+ if isinstance(request.data, AsyncIterable):+ chunks: list[bytes] = []+ try:+ async for chunk in request.data:+ if isinstance(chunk, str):+ chunks.append(chunk.encode())+ elif isinstance(chunk, bytes):+ chunks.append(chunk)+ else:+ # Handle unexpected types+ chunks.append(str(chunk).encode())+ return b"".join(chunks)+ except Exception as e:+ LOGGER.error(f"Error collecting async request body: {e}")+ raise+ if isinstance(request.data, str):+ return request.data.encode()+ if isinstance(request.data, bytes):+ return request.data+ if hasattr(request.data, "read"):+ return request.data.read() # type: ignore++ raise ValueError(+ f"Unsupported request data type: {type(request.data)}"+ )++ def _send_request(self, request: _URLRequest, body: bytes) -> HTTPResponse:+ from http.client import HTTPConnection++ parsed_url = urlparse(request.full_url)+ path_and_query = parsed_url.path+ if parsed_url.query:+ path_and_query += f"?{parsed_url.query}"++ conn_class = HTTPSConnection if self.is_https else HTTPConnection+ conn = conn_class(self.host, timeout=self.timeout)++ method = request.method or "GET"+try:- body = await collect_body()+ conn.request(+ method=method,+ url=path_and_query, # Only path and query+ body=body,+ headers=request.headers,+ )+ resp = conn.getresponse()+ return resp # type: ignore[no-any-return]except Exception:raise- def _send() -> HTTPResponse:- from http.client import HTTPConnection-- parsed_url = urlparse(request.full_url)- path_and_query = parsed_url.path- if parsed_url.query:- path_and_query += f"?{parsed_url.query}"-- conn_class = HTTPSConnection if self.is_https else HTTPConnection- conn = conn_class(self.host)+ async def send(+ self, request: _URLRequest, stream: bool = False, max_retries: int = 2+ ) -> _AsyncHTTPResponse:+ del stream+ loop = asyncio.get_event_loop()- method = request.method if request.method is not None else "GET"+ body = await self._collect_body(request)+ for attempt in range(max_retries + 1):try:- conn.request(- method=method,- url=path_and_query, # Only path and query- body=body,- headers=request.headers,+ response = await loop.run_in_executor(+ None, lambda: self._send_request(request, body))- resp = conn.getresponse()- return resp # type: ignore[no-any-return]- except Exception:- raise-- response = await loop.run_in_executor(None, _send)- return _AsyncHTTPResponse(response)+ return _AsyncHTTPResponse(response)+ except (ConnectionError, TimeoutError) as e:+ if attempt < max_retries:+ # Exponential backoff+ wait_time = 0.1 * (2**attempt)+ LOGGER.warning(+ f"Connection attempt {attempt + 1} failed: {e}. Retrying in {wait_time}s..."+ )+ await asyncio.sleep(wait_time)+ else:+ LOGGER.error(f"All connection attempts failed: {e}")+ raise++ raise ValueError("Failed to send request")class ProxyMiddleware:@@ -397,66 +416,74 @@ class ProxyMiddleware:self, scope: Scope, receive: Receive, send: Send, ws_url: str) -> None:websocket = WebSocket(scope, receive=receive, send=send)- original_params = websocket.query_params- if original_params:- ws_url = f"{ws_url}?{'&'.join(f'{k}={v}' for k, v in original_params.items())}"- await websocket.accept()+ try:+ original_params = websocket.query_params+ if original_params:+ ws_url = f"{ws_url}?{'&'.join(f'{k}={v}' for k, v in original_params.items())}"+ await websocket.accept()- async with connect(ws_url) as ws_client:+ async with connect(ws_url) as ws_client:++ async def client_to_upstream() -> None:+ try:+ while True:+ msg = await websocket.receive()+ if msg["type"] == "websocket.disconnect":+ # Cancel the other task when client disconnects+ for task in relay_tasks:+ if not task.done():+ task.cancel()+ return++ if "text" in msg:+ await ws_client.send(msg["text"])+ elif "bytes" in msg:+ await ws_client.send(msg["bytes"])+ except Exception as e:+ LOGGER.error(f"Client to upstream relay error: {e}")+ # Cancel other tasks only if this is a fatal error+ for task in relay_tasks:+ if not task.done():+ task.cancel()++ async def upstream_to_client() -> None:+ try:+ while True:+ msg = await ws_client.recv()+ if isinstance(msg, bytes):+ await websocket.send_bytes(msg)+ else:+ await websocket.send_text(msg)+ except ConnectionClosed:+ # Cancel the other task when connection closes+ for task in relay_tasks:+ if not task.done():+ task.cancel()+ return+ except Exception:+ return++ # Run both relay loops concurrently+ relay_tasks = [+ asyncio.create_task(client_to_upstream()),+ asyncio.create_task(upstream_to_client()),+ ]- async def client_to_upstream() -> None:- try:- while True:- msg = await websocket.receive()- if msg["type"] == "websocket.disconnect":- # Cancel the other task when client disconnects- for task in relay_tasks:- if not task.done():- task.cancel()- return-- if "text" in msg:- await ws_client.send(msg["text"])- elif "bytes" in msg:- await ws_client.send(msg["bytes"])- except ConnectionClosed:- return- except Exception:- return-- async def upstream_to_client() -> None:try:- while True:- msg = await ws_client.recv()- if isinstance(msg, bytes):- await websocket.send_bytes(msg)- else:- await websocket.send_text(msg)- except ConnectionClosed:- # Cancel the other task when connection closes+ await asyncio.gather(*relay_tasks)+ except asyncio.CancelledError:+ pass+ except Exception as e:+ raise e+ finally:for task in relay_tasks:if not task.done():task.cancel()- return- except Exception:- return-- # Run both relay loops concurrently- relay_tasks = [- asyncio.create_task(client_to_upstream()),- asyncio.create_task(upstream_to_client()),- ]-- try:- await asyncio.gather(*relay_tasks)- except asyncio.CancelledError:- pass- except Exception as e:- raise e- finally:- for task in relay_tasks:- if not task.done():- task.cancel()- if websocket.client_state != WebSocketState.DISCONNECTED:- await websocket.close()- await ws_client.close()+ if websocket.client_state != WebSocketState.DISCONNECTED:+ await websocket.close()+ await ws_client.close()+ except Exception as e:+ LOGGER.error(f"WebSocket proxy error: {e}")+ if websocket.client_state != WebSocketState.DISCONNECTED:+ await websocket.close(code=1011) # Internal error+ raisediff --git a/pyproject.toml b/pyproject.tomlindex 4f0be09a2c..6e8340edda 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -68,6 +68,7 @@ classifiers = ["Programming Language :: Python :: 3.10","Programming Language :: Python :: 3.11","Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13","Programming Language :: Python :: 3 :: Only",]@@ -191,7 +192,6 @@ dependencies = ["polars~=1.9.0","narwhals>=1.12.0","matplotlib>=3.8.0",- "pyarrow-stubs>=17.0","sqlglot>=23.4","sqlalchemy>=2.0.0","pandas-stubs>=1.5.3.230321",@@ -219,7 +219,7 @@ extra-dependencies = [][[tool.hatch.envs.test.matrix]]-python = ["3.9", "3.10", "3.11", "3.12"]+python = ["3.9", "3.10", "3.11", "3.12", "3.13"][tool.hatch.envs.test.scripts]test = "pytest{env:HATCH_TEST_ARGS:} {args:tests}"@@ -248,7 +248,7 @@ extra-dependencies = [# For testing mo.ui.chart, table, ..."vl-convert-python","vegafusion",- "pyarrow",+ "pyarrow>=19.0.0","pyarrow_hotfix","altair>=5.4.0","polars~=1.24.0",@@ -259,7 +259,7 @@ extra-dependencies = [# Causes issues installing `shapely` (v2.0.7)# "geopandas~=1.0.1; python_version > '3.9'",# FOr testing sql- "ibis-framework[duckdb]~=9.5.0; python_version > '3.9'",+ "ibis-framework[duckdb]>=10.3.0; python_version > '3.9'",# For testing mo.image"pillow~=10.4.0","anywidget~=0.9.14",@@ -278,7 +278,7 @@ extra-dependencies = [][[tool.hatch.envs.test-optional.matrix]]-python = ["3.9", "3.10", "3.11", "3.12"]+python = ["3.9", "3.10", "3.11", "3.12", "3.13"][tool.hatch.envs.docs]features = ["dev", "docs"]diff --git a/tests/_messaging/test_console_output_worker.py b/tests/_messaging/test_console_output_worker.pyindex 2267e01827..225ede44d4 100644--- a/tests/_messaging/test_console_output_worker.py+++ b/tests/_messaging/test_console_output_worker.py@@ -231,6 +231,11 @@ class TestConsoleOutputWorker:# Use a longer timeout to ensure the messages are processedtime.sleep(TIMEOUT_S * 5)+ for _ in range(10):+ time.sleep(0.1)+ if len(stream.messages) == 2:+ break+# Check that the messages were written to the streamassert len(stream.messages) == 2 # Merged stdout messages + stderrdiff --git a/tests/_plugins/ui/_impl/tables/snapshots/ibis.csv b/tests/_plugins/ui/_impl/tables/snapshots/ibis.csvindex b09ce34dbc..c63db10fe3 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/ibis.csv+++ b/tests/_plugins/ui/_impl/tables/snapshots/ibis.csv@@ -1,4 +1,4 @@strings,bool,int,float,date,datetime,time,nulls-a,True,1,1.0,2021-01-01,2021-01-01 00:00:00,01:02:03,-b,False,2,2.0,2021-01-02,2021-01-02 00:00:00,04:05:06,data-c,True,3,3.0,2021-01-03,2021-01-03 00:00:00,07:08:09,+a,True,1,1.0,2021-01-01 00:00:00,2021-01-01 00:00:00,01:02:03,+b,False,2,2.0,2021-01-02 00:00:00,2021-01-02 00:00:00,04:05:06,data+c,True,3,3.0,2021-01-03 00:00:00,2021-01-03 00:00:00,07:08:09,diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.pyindex 6faeecec55..639b8f2d42 100644--- a/tests/_runtime/reload/test_module_watcher.py+++ b/tests/_runtime/reload/test_module_watcher.py@@ -16,7 +16,7 @@ from marimo._runtime.requests import SetUserConfigRequestfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-INTERVAL = 0.1+INTERVAL = 0.2@pytest.fixture(autouse=True)diff --git a/tests/_runtime/test_copy.py b/tests/_runtime/test_copy.pyindex 3697da98ec..307ee2ad72 100644--- a/tests/_runtime/test_copy.py+++ b/tests/_runtime/test_copy.py@@ -1,3 +1,5 @@+import sys+import pytestfrom marimo._runtime.copy import (@@ -25,6 +27,10 @@ def test_shadow_wrap() -> None:assert 1 + shadow == 2+ sys.version_info >= (3, 13),+ reason="__slots__ conflicts with class variable in Python 3.13",+)def test_shadow_wrap_ro_attr() -> None:class namespace: ...@@ -51,6 +57,10 @@ def test_shadow_wrap_ro_get() -> None:shadow[0] = 2+ sys.version_info >= (3, 13),+ reason="__slots__ conflicts with class variable in Python 3.13",+)def test_shadow_wrap_mutable_ref() -> None:class namespace: ...diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 262e6e0462..692e992453 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -1645,6 +1645,10 @@ class TestStrictExecution:assert k.globals["V1"] == 11@staticmethod+ @pytest.mark.xfail(+ sys.version_info >= (3, 13),+ reason="Namespace handling changes in Python 3.13",+ )async def test_cell_zero_copy_works(strict_kernel: Kernel, exec_req: ExecReqProvider) -> None:diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.pyindex 293320b662..3ccc788ccf 100644--- a/tests/_server/api/endpoints/test_execution.py+++ b/tests/_server/api/endpoints/test_execution.py@@ -2,9 +2,12 @@from __future__ import annotationsimport json+import sysimport timefrom typing import TYPE_CHECKING, Any+import pytest+from marimo._types.ids import CellId_t, SessionIdfrom marimo._utils.lists import firstfrom tests._server.conftest import get_session_manager@@ -160,6 +163,10 @@ class TestExecutionRoutes_EditMode:assert response.json()["status"] == "ok"@staticmethod+ @pytest.mark.skipif(+ sys.platform == "win32",+ reason="Skipping test on Windows due to websocket issues",+ )@with_session(SESSION_ID)def test_app_meta_request(client: TestClient) -> None:response = client.post(@@ -360,7 +367,7 @@ def get_printed_object(session = get_session_manager(client).get_session(SESSION_ID)assert session- timeout = 2+ timeout = 4start = time.time()console = Nonewhile time.time() - start < timeout:diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.pyindex 45d25ad022..663e5bcf43 100644--- a/tests/_server/api/test_middleware.py+++ b/tests/_server/api/test_middleware.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport ioimport json+import sysimport timefrom multiprocessing import Processfrom typing import TYPE_CHECKING, Any@@ -577,6 +578,10 @@ class TestProxyMiddleware:@pytest.mark.xfail(reason="Returning 403 instead of invalid ID message",)+ @pytest.mark.skipif(+ sys.platform == "win32",+ reason="Skipping test on Windows due to websocket issues",+ )def test_proxy_websocket_with_invalid_id(self, app_with_mpl_proxy: Starlette) -> None:diff --git a/tests/_server/export/snapshots/run_until_completion_with_stack_trace_py313.txt b/tests/_server/export/snapshots/run_until_completion_with_stack_trace_py313.txtnew file mode 100644index 0000000000..d85fcbbc38--- /dev/null+++ b/tests/_server/export/snapshots/run_until_completion_with_stack_trace_py313.txt@@ -0,0 +1,30 @@+[+ {+ "output": "",+ "console": [+ "running internal tests\n"+ ],+ "status": "idle"+ },+ {+ "output": "<pre style='font-size: 12px'>15</pre>",+ "console": [+ "internal error\n"+ ],+ "status": "idle"+ },+ {+ "output": [+ {+ "msg": "This cell raised an exception: ValueError('Failed to authenticate. The correct password is [REDACTED]')",+ "exception_type": "ValueError",+ "raising_cell": null,+ "type": "exception"+ }+ ],+ "console": [+ "<span class=\"codehilite\"><div class=\"highlight\"><pre><span></span><span class=\"gt\">Traceback (most recent call last):</span>\n "</span>, line <span class=\"m\">3</span>, in <span class=\"n\"><module></span>\n<span class=\"w\"> </span><span class=\"k\">raise</span> <span class=\"ne\">ValueError</span><span class=\"p\">(</span>\n<span class=\"w\"> </span> <span class=\"s2\">"Failed to authenticate. The correct password is '[REDACTED]'."</span>\n<span class=\"w\"> </span><span class=\"p\">)</span>\n<span class=\"gr\">ValueError</span>: <span class=\"n\">Failed to authenticate. The correct password is '[REDACTED]'.</span>\n</pre></div>\n</span>"+ ],+ "status": "idle"+ }+]diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.pyindex 67e7ac71a0..ad2a14e7a9 100644--- a/tests/_server/export/test_exporter.py+++ b/tests/_server/export/test_exporter.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import sysfrom typing import TYPE_CHECKING, Anyimport pytest@@ -262,6 +263,9 @@ async def test_run_until_completion_with_stop():snapshot("run_until_completion_with_stop.txt", _print_messages(cell_ops))+ sys.version_info >= (3, 13), reason="3.13 has different stack trace format"+)async def test_run_until_completion_with_stack_trace():app = App()@@ -294,9 +298,11 @@ async def test_run_until_completion_with_stack_trace():)assert did_error is Truecell_ops = [op for op in session_view.operations if isinstance(op, CellOp)]++ messages = _print_messages(cell_ops)snapshot("run_until_completion_with_stack_trace.txt",- _delete_lines_with_files(_print_messages(cell_ops)),+ _delete_lines_with_files(messages),)