Skip to content

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.

Speed up function `natural_sort` by 120% (#6975)

Saurabh Misra4f3b1ddbc625
diff --git a/marimo/_utils/files.py b/marimo/_utils/files.py
index 3ed051b87d..d127d427de 100644
--- a/marimo/_utils/files.py
+++ b/marimo/_utils/files.py
@@ -12,15 +12,13 @@ from marimo._utils import async_path
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Generator
+_SPLIT_NUMBERS = re.compile(r"([0-9]+)").split
-def natural_sort(filename: str) -> list[Union[int, str]]:
- def convert(text: str) -> Union[int, str]:
- return int(text) if text.isdigit() else text.lower()
-
- def alphanum_key(key: str) -> list[Union[int, str]]:
- return [convert(c) for c in re.split("([0-9]+)", key)]
- return alphanum_key(filename)
+def natural_sort(filename: str) -> list[Union[int, str]]:
+ return [
+ int(c) if c.isdigit() else c.lower() for c in _SPLIT_NUMBERS(filename)
+ ]
def get_files(folder: str) -> Generator[Path, None, None]: