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
chore: use Path over open (#4005)
Myles Scolnickfa5ed75bfd6e
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex d28683957f..b197eb3760 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -311,7 +311,11 @@ edit_help_msg = "\n".join(type=bool,help="Watch the file for changes and reload the code when saved in another editor.",)[email protected]("name", required=False, type=click.Path())+ "name",+ required=False,+ type=click.Path(),+)@click.argument("args", nargs=-1, type=click.UNPROCESSED)def edit(port: Optional[int],@@ -404,7 +408,7 @@ def edit(elif not is_dir:# write empty filetry:- with open(name, "w"):+ with open(name, "w", encoding="utf-8"):passexcept OSError as e:if isinstance(e, FileNotFoundError):@@ -642,7 +646,11 @@ Example:type=bool,help=sandbox_message,)[email protected]("name", required=True, type=click.Path())+ "name",+ required=True,+ type=click.Path(),+)@click.argument("args", nargs=-1, type=click.UNPROCESSED)def run(port: Optional[int],diff --git a/marimo/_cli/convert/commands.py b/marimo/_cli/convert/commands.pyindex d3bd11a097..fe4134eedb 100644--- a/marimo/_cli/convert/commands.py+++ b/marimo/_cli/convert/commands.py@@ -16,7 +16,7 @@ from marimo._utils.paths import maybe_make_dirs@click.option("-o","--output",- type=click.Path(),+ type=click.Path(path_type=Path),default=None,help=("Output file to save the converted notebook to. "@@ -25,7 +25,7 @@ from marimo._utils.paths import maybe_make_dirs)def convert(filename: str,- output: str,+ output: Path,) -> None:r"""Convert a Jupyter notebook or Markdown file to a marimo notebook.@@ -64,8 +64,7 @@ def convert(if output:# Make dirs if neededmaybe_make_dirs(output)- with open(output, "w", encoding="utf-8") as f:- f.write(notebook)+ Path(output).write_text(notebook, encoding="utf-8")echo(f"Converted notebook saved to {output}")else:echo(notebook)diff --git a/marimo/_cli/convert/utils.py b/marimo/_cli/convert/utils.pyindex abbc631e5d..d6f5607a53 100644--- a/marimo/_cli/convert/utils.py+++ b/marimo/_cli/convert/utils.py@@ -2,6 +2,7 @@from __future__ import annotationsimport urllib.request+from pathlib import Pathfrom marimo._cli.file_path import get_github_src_url, is_github_src@@ -15,7 +16,6 @@ def load_external_file(file_path: str, ext: str) -> str:.decode("utf-8"))else:- with open(file_path, encoding="utf-8") as f:- notebook = f.read()+ notebook = Path(file_path).read_text(encoding="utf-8")return notebookdiff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 5f98940f84..179233d75b 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -5,6 +5,7 @@ import astimport osimport subprocessimport sys+from pathlib import Pathfrom typing import TYPE_CHECKING, Anyimport click@@ -336,7 +337,6 @@ def killall() -> None:marimo development ps killall"""- import osfor proc in get_marimo_processes():# Ignore self@@ -354,9 +354,11 @@ def killall() -> None:@click.argument("name",required=True,- type=click.Path(exists=True, file_okay=True, dir_okay=False),+ type=click.Path(+ path_type=Path, exists=True, file_okay=True, dir_okay=False+ ),)-def inline_packages(name: str) -> None:+def inline_packages(name: Path) -> None:"""Example usage:@@ -380,8 +382,8 @@ def inline_packages(name: str) -> None:)# Validate the file exists- if not os.path.exists(name):- raise click.FileError(name)+ if not name.exists():+ raise click.FileError(str(name))# Validate >=3.10 for sys.stdlib_module_namesif sys.version_info < (3, 10):@@ -393,8 +395,7 @@ def inline_packages(name: str) -> None:package_names = module_name_to_pypi_name()def get_pypi_package_names() -> list[str]:- with open(name) as file:- tree = ast.parse(file.read(), filename=name)+ tree = ast.parse(name.read_text(encoding="utf-8"), filename=name)imported_modules = set[str]()@@ -428,7 +429,7 @@ def inline_packages(name: str) -> None:"uv","add","--script",- name,+ str(name),]+ pypi_names)diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 2e5d7fe8a3..68dec110ce 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -2,7 +2,6 @@from __future__ import annotationsimport asyncio-import osfrom pathlib import Pathfrom typing import Callable, Literal, Optional@@ -45,7 +44,7 @@ def export() -> None:def watch_and_export(marimo_path: MarimoPath,- output: Optional[str],+ output: Optional[Path],watch: bool,export_callback: Callable[[MarimoPath], ExportResult],) -> None:@@ -59,9 +58,7 @@ def watch_and_export(if output:# Make dirs if neededmaybe_make_dirs(output)- with open(output, "w", encoding="utf-8") as f:- f.write(data)- f.close()+ output.write_text(data, encoding="utf-8")else:echo(data)return@@ -79,7 +76,7 @@ def watch_and_export(async def on_file_changed(file_path: Path) -> None:if output:echo(- f"File {str(file_path)} changed. Re-exporting to {green(output)}"+ f"File {str(file_path)} changed. Re-exporting to {green(str(output))}")result = export_callback(MarimoPath(file_path))write_data(result.contents)@@ -128,7 +125,7 @@ Optionally pass CLI args to the notebook:@click.option("-o","--output",- type=click.Path(),+ type=click.Path(path_type=Path),default=None,help=("Output file to save the HTML to. "@@ -152,7 +149,7 @@ Optionally pass CLI args to the notebook:def html(name: str,include_code: bool,- output: str,+ output: Path,watch: bool,sandbox: Optional[bool],args: tuple[str],@@ -209,7 +206,7 @@ Watch for changes and regenerate the script on modification:@click.option("-o","--output",- type=click.Path(),+ type=click.Path(path_type=Path),default=None,help=("Output file to save the script to. "@@ -231,7 +228,7 @@ Watch for changes and regenerate the script on modification:)def script(name: str,- output: str,+ output: Path,watch: bool,sandbox: Optional[bool],) -> None:@@ -281,7 +278,7 @@ Watch for changes and regenerate the script on modification:@click.option("-o","--output",- type=click.Path(),+ type=click.Path(path_type=Path),default=None,help=("Output file to save the markdown to. "@@ -303,7 +300,7 @@ Watch for changes and regenerate the script on modification:)def md(name: str,- output: str,+ output: Path,watch: bool,sandbox: Optional[bool],) -> None:@@ -362,7 +359,7 @@ Requires nbformat to be installed.@click.option("-o","--output",- type=click.Path(),+ type=click.Path(path_type=Path),default=None,help=("Output file to save the ipynb file to. "@@ -391,7 +388,7 @@ Requires nbformat to be installed.)def ipynb(name: str,- output: str,+ output: Path,watch: bool,sort: Literal["top-down", "topological"],include_outputs: bool,@@ -453,7 +450,7 @@ and cannot be opened directly from the file system (e.g. file://).@click.option("-o","--output",- type=click.Path(),+ type=click.Path(path_type=Path),required=True,help="Output directory to save the HTML to.",)@@ -495,7 +492,7 @@ and cannot be opened directly from the file system (e.g. file://).)def html_wasm(name: str,- output: str,+ output: Path,mode: Literal["edit", "run"],watch: bool,show_code: bool,@@ -520,9 +517,9 @@ def html_wasm(filename = "index.html"ignore_index_html = False# If ends with .html, get the directory- if output.endswith(".html"):- out_dir = os.path.dirname(output)- filename = os.path.basename(output)+ if output.suffix == ".html":+ out_dir = output.parent+ filename = output.nameignore_index_html = Truemarimo_file = MarimoPath(name)@@ -538,7 +535,7 @@ def html_wasm((Path(out_dir) / ".nojekyll").touch()echo(- f"Assets copied to {green(out_dir)}. These assets are required for the "+ f"Assets copied to {green(str(out_dir))}. These assets are required for the ""notebook to run in the browser.")@@ -546,7 +543,7 @@ def html_wasm(if did_export_public:echo(f"The public folder next to your notebook was copied to "- f"{green(out_dir)}."+ f"{green(str(out_dir))}.")echo(@@ -555,7 +552,7 @@ def html_wasm("Then open the URL that is printed to your terminal.")- outfile = os.path.join(out_dir, filename)+ outfile = out_dir / filenamereturn watch_and_export(MarimoPath(name), outfile, watch, export_callback)diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pyindex 1b51dd2396..71e3ade8f7 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/file_path.py@@ -4,9 +4,9 @@ from __future__ import annotationsimport abcimport jsonimport os-import pathlibimport urllib.parseimport urllib.request+from pathlib import Pathfrom tempfile import TemporaryDirectoryfrom typing import Optionalfrom urllib.error import HTTPError@@ -55,12 +55,12 @@ class LocalFileReader(FileReader):return not is_url(name)def read(self, name: str) -> tuple[str, str]:+ file_path = Path(name)# Is directory- if os.path.isdir(name):- return "", os.path.basename(name)- with open(name, encoding="utf-8") as f:- content = f.read()- return content, os.path.basename(name)+ if file_path.is_dir():+ return "", file_path.name+ content = file_path.read_text(encoding="utf-8")+ return content, file_path.nameclass GitHubIssueReader(FileReader):@@ -222,9 +222,9 @@ class LocalFileHandler(FileHandler):del temp_dirimport click- path = pathlib.Path(name)+ path = Path(name)- if self.allow_directory and os.path.isdir(name):+ if self.allow_directory and path.is_dir():return name, Noneif path.suffix == ".ipynb":@@ -243,7 +243,7 @@ class LocalFileHandler(FileHandler):)if not self.allow_new_file:- if not os.path.exists(name):+ if not path.exists():raise click.ClickException(f"Invalid NAME - {name} does not exist")@@ -281,14 +281,13 @@ class RemoteFileHandler(FileHandler):content: str, name: str, temp_dir: TemporaryDirectory[str]) -> str:LOGGER.info("Creating temporary file")- path_to_app = os.path.join(temp_dir.name, name)+ path_to_app = Path(temp_dir.name) / name# If doesn't end in .py, add it- if not path_to_app.endswith(".py"):- path_to_app += ".py"- with open(path_to_app, "w", encoding="utf-8") as f:- f.write(content)+ if not path_to_app.suffix == ".py":+ path_to_app = path_to_app.with_suffix(".py")+ path_to_app.write_text(content, encoding="utf-8")LOGGER.info("App saved to %s", path_to_app)- return path_to_app+ return str(path_to_app)def validate_name(diff --git a/marimo/_plugins/core/media.py b/marimo/_plugins/core/media.pyindex e46c34c9cd..5e37f62997 100644--- a/marimo/_plugins/core/media.py+++ b/marimo/_plugins/core/media.py@@ -112,8 +112,7 @@ def io_to_data_url(# Handle pathlib.Pathif isinstance(src, pathlib.Path):- with open(src, "rb") as f:- return io_to_data_url(f, fallback_mime_type)+ return io_to_data_url(src.read_bytes(), fallback_mime_type)# Handle strings - check if it's a URLif isinstance(src, str):diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 184cf1945f..b3102a5f28 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -6,6 +6,7 @@ import base64import dataclassesimport jsonimport signal+from pathlib import Pathfrom typing import Any, Callable, Optionalfrom marimo import _loggers@@ -290,8 +291,7 @@ class PyodideBridge:) -> str:body = parse_raw(json.loads(request), FileUpdateRequest)try:- with open(body.path, "w") as file:- file.write(body.contents)+ Path(body.path).write_text(body.contents)response = FileUpdateResponse(success=True)except Exception as e:response = FileUpdateResponse(success=False, message=str(e))diff --git a/marimo/_runtime/layout/layout.py b/marimo/_runtime/layout/layout.pyindex 274c563b36..534af31256 100644--- a/marimo/_runtime/layout/layout.py+++ b/marimo/_runtime/layout/layout.py@@ -36,7 +36,6 @@ def save_layout_config(Returns: the path to the layout file"""-# remove py extensionapp_name_without_ext = app_name.replace(".py", "")# relative file path@@ -45,7 +44,7 @@ def save_layout_config(full_filepath = os.path.join(directory, filepath)# create directory if it doesn't existos.makedirs(os.path.dirname(full_filepath), exist_ok=True)- with open(full_filepath, "w") as f:+ with open(full_filepath, "w", encoding="utf-8") as f:json.dump(config.__dict__, f, indent=2)return filepath@@ -77,6 +76,6 @@ def read_layout_config(if not filepath.endswith(".json"):LOGGER.warning("Layout file %s is not a JSON file", filepath)return None- with open(filepath) as f:+ with open(filepath, encoding="utf-8") as f:data = json.load(f)return LayoutConfig(type=data["type"], data=data["data"]) # type: ignore[call-overload]diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 40f107a912..1d91770a08 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -51,7 +51,7 @@ from marimo._utils.paths import import_filesLOGGER = _loggers.marimo_logger()# Root directory for static assets-root = os.path.realpath(str(import_files("marimo").joinpath("_static")))+root: str = os.path.realpath(str(import_files("marimo").joinpath("_static")))if TYPE_CHECKING:from nbformat.notebooknode import NotebookNode # type: ignore@@ -385,7 +385,7 @@ class Exporter:return html, download_filenamedef export_assets(- self, directory: str, ignore_index_html: bool = False+ self, directory: Path, ignore_index_html: bool = False) -> None:# Copy assets to the same directory as the notebookdirpath = Path(directory)@@ -407,7 +407,7 @@ class Exporter:)def export_public_folder(- self, directory: str, marimo_file: MarimoPath+ self, directory: Path, marimo_file: MarimoPath) -> bool:FOLDER_NAME = "public"public_dir = marimo_file.path.parent / FOLDER_NAME@@ -441,52 +441,49 @@ class AutoExporter:def save_html(self, file_manager: AppFileManager, html: str) -> None:# get filename- directory = os.path.dirname(get_filename(file_manager))+ directory = Path(get_filename(file_manager)).parentfilename = get_download_filename(file_manager, "html")# make directory if it doesn't existself._make_export_dir(directory)- filepath = os.path.join(directory, self.EXPORT_DIR, filename)+ filepath = directory / self.EXPORT_DIR / filename# save html to .marimo directory- with open(filepath, "w") as f:- f.write(html)+ filepath.write_text(html, encoding="utf-8")def save_md(self, file_manager: AppFileManager, markdown: str) -> None:# get filename- directory = os.path.dirname(get_filename(file_manager))+ directory = Path(get_filename(file_manager)).parentfilename = get_download_filename(file_manager, "md")# make directory if it doesn't existself._make_export_dir(directory)- filepath = os.path.join(directory, self.EXPORT_DIR, filename)+ filepath = directory / self.EXPORT_DIR / filename# save md to .marimo directory- with open(filepath, "w") as f:- f.write(markdown)+ filepath.write_text(markdown, encoding="utf-8")def save_ipynb(self, file_manager: AppFileManager, ipynb: str) -> None:# get filename- directory = os.path.dirname(get_filename(file_manager))+ directory = Path(get_filename(file_manager)).parentfilename = get_download_filename(file_manager, "ipynb")# make directory if it doesn't existself._make_export_dir(directory)- filepath = os.path.join(directory, self.EXPORT_DIR, filename)+ filepath = directory / self.EXPORT_DIR / filename# save ipynb to .marimo directory- with open(filepath, "w") as f:- f.write(ipynb)+ filepath.write_text(ipynb, encoding="utf-8")- def _make_export_dir(self, directory: str) -> None:+ def _make_export_dir(self, directory: Path) -> None:# make .marimo dir if it doesn't exist# don't make the other directories- if not os.path.exists(directory):+ if not directory.exists():raise FileNotFoundError(f"Directory {directory} does not exist")- export_dir = os.path.join(directory, self.EXPORT_DIR)- if not os.path.exists(export_dir):- os.mkdir(export_dir)+ export_dir = directory / self.EXPORT_DIR+ if not export_dir.exists():+ export_dir.mkdir(parents=True, exist_ok=True)def hash_code(code: str) -> str:@@ -530,8 +527,8 @@ def get_html_contents() -> str:with urllib.request.urlopen(url) as response:return cast(str, response.read().decode("utf-8"))- with open(os.path.join(root, "index.html")) as f:- return f.read()+ index_html = Path(root) / "index.html"+ return index_html.read_text(encoding="utf-8")def _convert_marimo_output_to_ipynb(diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex 4ea0578e34..e3f0e0a0b1 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -4,7 +4,8 @@ from __future__ import annotationsimport osimport pathlibimport shutil-from typing import TYPE_CHECKING, Any, Optional, Union+from pathlib import Path+from typing import Any, Optional, Unionfrom marimo import _loggersfrom marimo._ast import codegen@@ -24,9 +25,6 @@ from marimo._server.models.models import (from marimo._server.utils import canonicalize_filenamefrom marimo._types.ids import CellId_t-if TYPE_CHECKING:- from pathlib import Path-LOGGER = _loggers.marimo_logger()@@ -100,8 +98,7 @@ class AppFileManager:) -> None:self._create_parent_directories(filename)try:- with open(filename, "w", encoding="utf-8") as f:- f.write(contents)+ Path(filename).write_text(contents, encoding="utf-8")except Exception as err:raise HTTPException(status_code=HTTPStatus.SERVER_ERROR,@@ -336,23 +333,20 @@ class AppFileManager:status_code=HTTPStatus.BAD_REQUEST,detail="Cannot read code from an unnamed notebook",)- with open(self.filename, encoding="utf-8") as f:- contents = f.read().strip()- return contents+ return Path(self.filename).read_text(encoding="utf-8")def read_css_file(css_file: str, filename: Optional[str]) -> Optional[str]:if not css_file or not filename:return None- app_dir = os.path.dirname(filename)- filepath = os.path.join(app_dir, css_file)- if not os.path.exists(filepath):+ app_dir = Path(filename).parent+ filepath = app_dir / css_file+ if not filepath.exists():LOGGER.error("CSS file %s does not exist", css_file)return Nonetry:- with open(filepath) as f:- return f.read()+ return filepath.read_text(encoding="utf-8")except OSError as e:LOGGER.warning("Failed to open custom CSS file %s for reading: %s",@@ -368,14 +362,13 @@ def read_html_head_file(if not html_head_file or not filename:return None- app_dir = os.path.dirname(filename)- filepath = os.path.join(app_dir, html_head_file)- if not os.path.exists(filepath):+ app_dir = Path(filename).parent+ filepath = app_dir / html_head_file+ if not filepath.exists():LOGGER.error("HTML head file %s does not exist", html_head_file)return Nonetry:- with open(filepath) as f:- return f.read()+ return filepath.read_text(encoding="utf-8")except OSError as e:LOGGER.warning("Failed to open HTML head file %s for reading: %s",diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex 151bac81e2..54da49e402 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -8,6 +8,7 @@ import platformimport reimport shutilimport subprocess+from pathlib import Pathfrom typing import Literal, Optional, Unionfrom marimo import _loggers@@ -97,11 +98,11 @@ class OSFileSystem(FileSystem):)def _is_marimo_file(self, path: str) -> bool:- if not path.endswith(".py"):+ file_path = Path(path)+ if not file_path.suffix == ".py":return False- with open(path, "rb") as file:- return b"app = marimo.App(" in file.read()+ return b"app = marimo.App(" in file_path.read_bytes()def open_file(self, path: str, encoding: str | None = None) -> str:try:@@ -126,28 +127,27 @@ class OSFileSystem(FileSystem):if name.strip() == "":raise ValueError("Cannot create file or directory with empty name")- full_path = os.path.join(path, name)+ full_path = Path(path) / name# If the file already exists, generate a new name- if os.path.exists(full_path):+ if full_path.exists():i = 1- name_without_extension, extension = os.path.splitext(name)+ name_without_extension = full_path.stem+ extension = full_path.suffixwhile True:new_name = f"{name_without_extension}_{i}{extension}"- new_full_path = os.path.join(path, new_name)- if not os.path.exists(new_full_path):+ new_full_path = full_path.parent / new_name+ if not new_full_path.exists():full_path = new_full_pathbreaki += 1if file_type == "directory":- os.makedirs(full_path)+ full_path.mkdir(parents=True, exist_ok=True)else:- with open(full_path, "wb") as file:- if contents:- file.write(contents)+ full_path.write_bytes(contents or b"")# encoding latin-1 to get an invertible representation of the# bytes as a string ...- return self.get_details(full_path, encoding="latin-1").file+ return self.get_details(str(full_path), encoding="latin-1").filedef delete_file_or_directory(self, path: str) -> bool:if os.path.isdir(path):@@ -166,8 +166,8 @@ class OSFileSystem(FileSystem):return self.get_details(new_path).filedef update_file(self, path: str, contents: str) -> FileInfo:- with open(path, "w") as file:- file.write(contents)+ file_path = Path(path)+ file_path.write_text(contents)return self.get_details(path).filedef open_in_editor(self, path: str) -> bool:diff --git a/marimo/_tracer.py b/marimo/_tracer.pyindex 9b4f8813b1..19b3e2c1f8 100644--- a/marimo/_tracer.py+++ b/marimo/_tracer.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport osfrom contextlib import contextmanager+from pathlib import Pathfrom typing import TYPE_CHECKING, Any, castfrom marimo import _loggers@@ -104,13 +105,13 @@ def _set_tracer_provider() -> None:class FileExporter(SpanExporter):def __init__(self, file_path: str) -> None:- self.file_path: str = file_path+ self.file_path = Path(file_path)# Clear file- open(self.file_path, "w").close()+ self.file_path.write_bytes(b"")def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:try:- with open(self.file_path, "a") as f:+ with self.file_path.open("a", encoding="utf-8") as f:for span in spans:f.write(span.to_json(cast(Any, None)))f.write("\n")diff --git a/marimo/_utils/paths.py b/marimo/_utils/paths.pyindex b2c6eb6917..565b17558b 100644--- a/marimo/_utils/paths.py+++ b/marimo/_utils/paths.py@@ -2,7 +2,10 @@from __future__ import annotationsimport os-from typing import Any+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from pathlib import Pathdef import_files(filename: str) -> Any:@@ -29,10 +32,8 @@ def pretty_path(filename: str) -> str:return filename-def maybe_make_dirs(filepath: str) -> None:+def maybe_make_dirs(filepath: Path) -> None:"""Create directories if they don't exist."""- dirname = os.path.dirname(filepath)- if dirname:- os.makedirs(os.path.dirname(filepath), exist_ok=True)+ filepath.parent.mkdir(parents=True, exist_ok=True)diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.pyindex 9d8d2a3920..e9d6af1487 100644--- a/tests/_cli/test_cli.py+++ b/tests/_cli/test_cli.py@@ -18,6 +18,7 @@ import tempfileimport timeimport urllib.errorimport urllib.request+from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Optionalimport pytest@@ -32,7 +33,6 @@ from marimo._utils.toml import read_tomlif TYPE_CHECKING:from collections.abc import Generator, Iterator- from pathlib import PathHAS_UV = DependencyManager.which("uv")@@ -117,10 +117,9 @@ def _temp_run_file(directory: tempfile.TemporaryDirectory[str]) -> str:filecontents = codegen.generate_filecontents(["import marimo as mo"], ["one"], cell_configs=[CellConfig()])- path = os.path.join(directory.name, "run.py")- with open(path, "w", encoding="utf-8") as f:- f.write(filecontents)- return path+ path = Path(directory.name) / "run.py"+ path.write_text(filecontents, encoding="utf-8")+ return str(path)def _check_contents(diff --git a/tests/_cli/test_file_path.py b/tests/_cli/test_file_path.pyindex 4e84828741..69196ae462 100644--- a/tests/_cli/test_file_path.py+++ b/tests/_cli/test_file_path.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport tempfileimport urllib.error+from pathlib import Pathfrom unittest.mock import mock_open, patchimport click@@ -116,15 +117,16 @@ def test_github_source_reader() -> None:assert filename == "example.py"-def test_local_file_reader() -> None:+def test_local_file_reader(tmp_path: Path) -> None:reader = LocalFileReader()- assert reader.can_read("local_file.py") is True+ local_file = tmp_path / "local_file.py"+ local_file.write_text("print('Hello, world!')")+ assert reader.can_read(str(local_file)) is Trueassert reader.can_read("https://example.com/file.py") is False- with patch("builtins.open", mock_open(read_data="print('Hello, world!')")):- content, filename = reader.read("local_file.py")- assert content == "print('Hello, world!')"- assert filename == "local_file.py"+ content, filename = reader.read(str(local_file))+ assert content == "print('Hello, world!')"+ assert filename == "local_file.py"def test_static_notebook_reader() -> None:@@ -321,24 +323,32 @@ def test_github_source_reader_different_extensions():assert filename in ["example.py", "README.md"]-def test_local_file_reader_with_spaces():+def test_local_file_reader_with_spaces(tmp_path: Path):reader = LocalFileReader()filename = "file with spaces.py"- assert reader.can_read(filename) is True- with patch("builtins.open", mock_open(read_data="print('Hello, world!')")):- content, read_filename = reader.read(filename)- assert content == "print('Hello, world!')"- assert read_filename == filename+ file_path = tmp_path / filename+ file_path.write_text("print('Hello, world!')")++ assert reader.can_read(str(file_path)) is True++ content, read_filename = reader.read(str(file_path))+ assert content == "print('Hello, world!')"+ assert read_filename == filenamedef test_validate_name_with_relative_and_absolute_paths():- relative_path = "relative/path/file.py"- absolute_path = "/absolute/path/file.py"+ cwd = Path.cwd()+ rel_file = cwd / "temp_relative_file.py"+ abs_file = cwd / "temp_absolute_file.py"+ try:+ # Create relative path+ rel_file.touch()+ relative_path = str(rel_file.relative_to(cwd))++ # Create absolute path+ abs_file.touch()+ absolute_path = str(abs_file)- with (- patch("os.path.exists", return_value=True),- patch("pathlib.Path.is_file", return_value=True),- ):assert (validate_name(relative_path, allow_new_file=False, allow_directory=False@@ -351,3 +361,6 @@ def test_validate_name_with_relative_and_absolute_paths():)[0]== absolute_path)+ finally:+ Path.unlink(rel_file)+ Path.unlink(abs_file)diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex cdd9cfb40b..c67f0bed36 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -56,7 +56,7 @@ def test_read_code(client: TestClient) -> None:json={},)assert response.status_code == 200, response.text- assert response.json()["contents"].startswith("import marimo")+ assert response.json()["contents"].strip().startswith("import marimo")@with_session(SESSION_ID)diff --git a/tests/mocks.py b/tests/mocks.pyindex 4729ff5506..c9f00530e0 100644--- a/tests/mocks.py+++ b/tests/mocks.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport difflibimport os+from pathlib import Pathfrom typing import Callablefrom marimo import __version__@@ -22,9 +23,7 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:def snapshot(filename: str, result: str, keep_version: bool = False) -> None:- filepath = os.path.join(- os.path.dirname(current_file), "snapshots", filename- )+ filepath = Path(current_file).parent / "snapshots" / filenameif not keep_version:result = _sanitize_version(result)