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.

lint: unspecified encoding in text file operations (#4202)

Roman Leventov220153f8dd5c
diff --git a/docs/blocks.py b/docs/blocks.py
index 9445ddd608..8c24024c91 100644
--- a/docs/blocks.py
+++ b/docs/blocks.py
@@ -96,7 +96,7 @@ class MarimoEmbedFileBlock(BaseMarimoBlock):
# Read from project root
try:
- with open(filepath, "r") as f:
+ with open(filepath, "r", encoding="utf-8") as f:
code = f.read()
except FileNotFoundError:
raise ValueError(f"File not found: {filepath}")
diff --git a/examples/ai/data/data_labeler.py b/examples/ai/data/data_labeler.py
index 9ab9e7d67b..1abab7e77a 100644
--- a/examples/ai/data/data_labeler.py
+++ b/examples/ai/data/data_labeler.py
@@ -138,7 +138,7 @@ def __(json, os):
for _ in range(number_of_examples)
]
- with open(path, "r") as f:
+ with open(path, "r", encoding="utf-8") as f:
labels = json.loads(f.read())
assert len(labels) == number_of_examples
return labels
@@ -150,7 +150,7 @@ def __(json, os):
{"label": item["label"], "notes": item["notes"][:100]}
for item in labels
]
- with open(path, "w") as f:
+ with open(path, "w", encoding="utf-8") as f:
f.write(json.dumps(labels))
return load_labels, write_labels
diff --git a/examples/ai/data/model_comparison.py b/examples/ai/data/model_comparison.py
index 5281d50724..adb3abf92c 100644
--- a/examples/ai/data/model_comparison.py
+++ b/examples/ai/data/model_comparison.py
@@ -190,7 +190,7 @@ def __(json, os):
for _ in range(number_of_examples)
]
- with open(path, "r") as f:
+ with open(path, "r", encoding="utf-8") as f:
choices = json.loads(f.read())
assert len(choices) == number_of_examples
return choices
@@ -198,7 +198,7 @@ def __(json, os):
def write_choices(choices, path):
# Trunacate notes
- with open(path, "w") as f:
+ with open(path, "w", encoding="utf-8") as f:
f.write(json.dumps(choices))
return load_choices, write_choices
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 4115ec4641..efd673b305 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -215,7 +215,7 @@ def construct_uv_command(
uv_cmd = ["uv", "run"]
with tempfile.NamedTemporaryFile(
- mode="w", delete=False, suffix=".txt"
+ mode="w", delete=False, suffix=".txt", encoding="utf-8"
) as temp_file:
temp_file_path = temp_file.name
uv_cmd.extend(
diff --git a/marimo/_config/utils.py b/marimo/_config/utils.py
index 699d6a879b..4728647633 100644
--- a/marimo/_config/utils.py
+++ b/marimo/_config/utils.py
@@ -51,7 +51,7 @@ def get_or_create_user_config_path() -> str:
else:
config_path = _xdg_config_path()
os.makedirs(os.path.dirname(config_path), exist_ok=True)
- open(config_path, "a").close()
+ open(config_path, "ab", buffering=0).close()
return config_path
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index c7fecf28a9..4aaa83a8de 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -319,7 +319,7 @@ class PyodideBridge:
) -> str:
body = parse_raw(json.loads(request), FileUpdateRequest)
try:
- Path(body.path).write_text(body.contents)
+ Path(body.path).write_text(body.contents, encoding="utf-8")
response = FileUpdateResponse(success=True)
except Exception as e:
response = FileUpdateResponse(success=False, message=str(e))
diff --git a/marimo/_pyodide/restartable_task.py b/marimo/_pyodide/restartable_task.py
index 54410bcc89..bb7dee8c19 100644
--- a/marimo/_pyodide/restartable_task.py
+++ b/marimo/_pyodide/restartable_task.py
@@ -1,3 +1,4 @@
+# Copyright 2025 Marimo. All rights reserved.
import asyncio
from typing import Any, Callable, Optional
diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.py
index 362256cb94..7215dca5c5 100644
--- a/marimo/_runtime/packages/pypi_package_manager.py
+++ b/marimo/_runtime/packages/pypi_package_manager.py
@@ -210,7 +210,7 @@ class UvPackageManager(PypiPackageManager):
)
# Get script metadata
- with open(filepath) as f:
+ with open(filepath, encoding="utf-8") as f:
frontmatter, body = extract_frontmatter(f.read())
headers = get_headers_from_frontmatter(frontmatter)
pyproject = bool(headers.get("pyproject", ""))
@@ -223,7 +223,7 @@ class UvPackageManager(PypiPackageManager):
# Write out and process the header
with tempfile.NamedTemporaryFile(
- mode="w", delete=False, suffix=".py"
+ mode="w", delete=False, suffix=".py", encoding="utf-8"
) as temp_file:
temp_file.write(header)
temp_file.flush()
@@ -233,7 +233,7 @@ class UvPackageManager(PypiPackageManager):
packages_to_add,
packages_to_remove,
)
- with open(temp_file.name) as f:
+ with open(temp_file.name, encoding="utf-8") as f:
header = f.read()
# Clean up the temporary file
os.unlink(temp_file.name)
@@ -254,7 +254,7 @@ class UvPackageManager(PypiPackageManager):
sort_keys=False,
)
document = ["---", header.strip(), "---", body]
- with open(filepath, "w") as f:
+ with open(filepath, "w", encoding="utf-8") as f:
f.write("\n".join(document))
def _process_changes(
diff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.py
index 17621a01e1..86f7b1aaf2 100644
--- a/marimo/_server/api/utils.py
+++ b/marimo/_server/api/utils.py
@@ -41,23 +41,22 @@ def open_url_in_browser(browser: str, url: str) -> None:
Open a browser to the given URL.
"""
if which("xdg-open") is not None and browser == "default":
- with open(os.devnull, "w") as devnull:
- if (
- sys.platform == "win32"
- or sys.platform == "cygwin"
- or sys.implementation.name == "graalpy"
- ):
- preexec_fn = None
- else:
- preexec_fn = os.setpgrp
- subprocess.Popen(
- ["xdg-open", url],
- # don't forward signals: ctrl-c shouldn't kill the browser
- # TODO: test/workaround on windows
- preexec_fn=preexec_fn,
- stdout=devnull,
- stderr=subprocess.STDOUT,
- )
+ if (
+ sys.platform == "win32"
+ or sys.platform == "cygwin"
+ or sys.implementation.name == "graalpy"
+ ):
+ preexec_fn = None
+ else:
+ preexec_fn = os.setpgrp
+ subprocess.Popen(
+ ["xdg-open", url],
+ # don't forward signals: ctrl-c shouldn't kill the browser
+ # TODO: test/workaround on windows
+ preexec_fn=preexec_fn,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.STDOUT,
+ )
else:
if browser == "default":
webbrowser.open(url)
diff --git a/marimo/_utils/config/config.py b/marimo/_utils/config/config.py
index fcb022b4d0..17b702f2d9 100644
--- a/marimo/_utils/config/config.py
+++ b/marimo/_utils/config/config.py
@@ -48,7 +48,7 @@ class ConfigReader:
# None values is not valid toml, so we remove them
dict_data = {k: v for k, v in dict_data.items() if v is not None}
- with open(self.filepath, "w") as file:
+ with open(self.filepath, "w", encoding="utf-8") as file:
tomlkit.dump(dict_data, file)
@staticmethod
diff --git a/pyproject.toml b/pyproject.toml
index a44ab52fe5..84c7a8584f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -405,6 +405,7 @@ extend-select = [
"D211", # No blank lines allowed before class docstring
"D214", # Section is over-indented
"D215", # Section underline is over-indented
+ "PLW1514", # Unspecified encoding in open()
"UP", # Upgrades
]
@@ -415,7 +416,7 @@ unfixable = ["F401"]
convention = "google"
[tool.ruff.lint.per-file-ignores]
-"**/{tests}/*" = ["ANN201", "ANN202", "T201", "D", "F841"]
+"**/{tests}/*" = ["ANN201", "ANN202", "T201", "D", "F841", "PLW1514"]
"dagger/*" = ["TID252"]
[tool.ruff.lint.isort]
diff --git a/scripts/analyze_traces.py b/scripts/analyze_traces.py
index 0d9cc0a155..56aa9e7dac 100644
--- a/scripts/analyze_traces.py
+++ b/scripts/analyze_traces.py
@@ -111,7 +111,7 @@ def __():
def __(Dict, List, Span, json):
def parse_jsonl(file_path):
spans = []
- with open(file_path, "r") as file:
+ with open(file_path, "r", encoding="utf-8") as file:
for line in file:
spans.append(Span.parse(json.loads(line)))
return spans