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(ruff): close files with context managers (#10952)
Shahmir Varqha043b7c723cdb
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex bf2b4e4487..d85bded033 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -473,14 +473,13 @@ def run_in_sandbox(write_constraint_file,)- constraint_tmp = tempfile.NamedTemporaryFile(+ with tempfile.NamedTemporaryFile(mode="w",delete=False,suffix="-pyodide-constraints.txt",encoding="utf-8",- )- constraint_tmp.close()- constraint_path = constraint_tmp.name+ ) as constraint_tmp:+ constraint_path = constraint_tmp.nameif write_constraint_file(constraint_path):# Resolution happens in the child uv process; see below.env["UV_CONSTRAINT"] = constraint_pathdiff --git a/marimo/_plugins/stateless/audio.py b/marimo/_plugins/stateless/audio.pyindex 4df324bb73..c33f7307be 100644--- a/marimo/_plugins/stateless/audio.py+++ b/marimo/_plugins/stateless/audio.py@@ -47,15 +47,13 @@ def convert_numpy_to_wav(scaled_bytes = scaled.astype("<h").tobytes()buffer = io.BytesIO()- waveobj = wave.open(buffer, mode="wb")- waveobj.setnchannels(nchannels)- waveobj.setframerate(rate)- waveobj.setsampwidth(2)- waveobj.setcomptype("NONE", "NONE")- waveobj.writeframes(scaled_bytes)- val = buffer.getvalue()- waveobj.close()- return val+ with wave.open(buffer, mode="wb") as waveobj:+ waveobj.setnchannels(nchannels)+ waveobj.setframerate(rate)+ waveobj.setsampwidth(2)+ waveobj.setcomptype("NONE", "NONE")+ waveobj.writeframes(scaled_bytes)+ return buffer.getvalue()def get_resolved_src(diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex 0184cea0e7..ea49d350bb 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -277,18 +277,18 @@ class OSFileSystem(FileSystem):# picking a unique name and writing to it.full_path = _claim_unique_path(parent / name)- tmp = tempfile.NamedTemporaryFile(- dir=full_path.parent,- prefix=full_path.name + ".",- suffix=".part",- delete=False,- )- tmp_path = tmp.name+ tmp_path: str | None = Nonetry:- # Sync writes are bounded to one chunk between awaits, so event- # loop blockage stays small without pulling in aiofiles.- written = 0- with tmp:+ with tempfile.NamedTemporaryFile(+ dir=full_path.parent,+ prefix=full_path.name + ".",+ suffix=".part",+ delete=False,+ ) as tmp:+ tmp_path = tmp.name+ # Sync writes are bounded to one chunk between awaits, so event+ # loop blockage stays small without pulling in aiofiles.+ written = 0while chunk := await source.read(_STREAM_CHUNK_SIZE):written += len(chunk)if written > MAX_UPLOAD_BYTES:@@ -297,11 +297,17 @@ class OSFileSystem(FileSystem):f"{MAX_UPLOAD_BYTES} bytes")tmp.write(chunk)+ assert tmp_path is not Noneos.replace(tmp_path, full_path)except BaseException:# Both paths may or may not exist depending on where we failed;# FileNotFoundError on either is expected.- for p in (tmp_path, str(full_path)):+ paths = (+ [str(full_path)]+ if tmp_path is None+ else [tmp_path, str(full_path)]+ )+ for p in paths:try:os.unlink(p)except FileNotFoundError:diff --git a/pyproject.toml b/pyproject.tomlindex 6917c07f49..93d25d3231 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -370,7 +370,6 @@ ignore = ["RUF012", # Mutable class default"S102", # Use of `exec`"DTZ005", # `datetime.now()` called without `tzinfo`- "SIM115", # Open file without context handler"DTZ006", # `datetime.fromtimestamp()` called without `tzinfo`"DTZ007", # `datetime.strptime()` called without zone"DTZ011", # `date.today()` useddiff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex 3f1500f15e..1d94f05b4b 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -400,7 +400,7 @@ def test_copy_file(client: TestClient) -> None:assert filename_copy in response.textdef _assert_contents():- file_contents = open(copied_file).read()+ file_contents = Path(copied_file).read_text()assert "import marimo as mo" in file_contentsassert 'marimo.App(width="full"' in file_contentsdiff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex 0c395e2bfe..5d6659f6d1 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -56,10 +56,9 @@ def get_starlette_server_state_init(def get_mock_session_manager(mode: SessionMode = SessionMode.EDIT,) -> SessionManager:- temp_file = tempfile.NamedTemporaryFile(suffix=".py", delete=False)-- temp_file.write(- b"""+ with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as temp_file:+ temp_file.write(+ b"""import marimo__generated_with = "0.0.1"@@ -75,14 +74,13 @@ def __():if __name__ == "__main__":app.run()"""- )-- temp_file.close()+ )+ temp_file_path = temp_file.namelsp_server = NoopLspServer()sm = SessionManager(- workspace=SingleFileWorkspace.from_path(MarimoPath(temp_file.name)),+ workspace=SingleFileWorkspace.from_path(MarimoPath(temp_file_path)),mode=mode,quiet=False,include_code=True,diff --git a/tests/_server/test_workspace.py b/tests/_server/test_workspace.pyindex 786354876b..3a38108822 100644--- a/tests/_server/test_workspace.py+++ b/tests/_server/test_workspace.py@@ -45,14 +45,15 @@ class TestNotebookWorkspace(unittest.TestCase):def setUp(self):# Create a temporary directoryself.test_dir = tempfile.mkdtemp()- # Create temporary files- self.test_file1 = tempfile.NamedTemporaryFile(+ # Keep file objects on self because tests use their `.name` paths+ # after setup; each handle is closed immediately after writing.+ self.test_file1 = tempfile.NamedTemporaryFile( # noqa: SIM115delete=False, dir=self.test_dir, suffix=".py")- self.test_file2 = tempfile.NamedTemporaryFile(+ self.test_file2 = tempfile.NamedTemporaryFile( # noqa: SIM115delete=False, dir=self.test_dir, suffix=".py")- self.test_file_3 = tempfile.NamedTemporaryFile(+ self.test_file_3 = tempfile.NamedTemporaryFile( # noqa: SIM115delete=False, dir=self.test_dir, suffix=".md")# Write to the temporary files@@ -66,7 +67,7 @@ class TestNotebookWorkspace(unittest.TestCase):# Create a nested directory and fileself.nested_dir = os.path.join(self.test_dir, "nested")os.mkdir(self.nested_dir)- self.nested_file = tempfile.NamedTemporaryFile(+ self.nested_file = tempfile.NamedTemporaryFile( # noqa: SIM115delete=False, dir=self.nested_dir, suffix=".py")self.nested_file.write(file_contents.encode())