Skip to content

tests: accept a positional encoding on Path.read_text / write_text - #13646

Merged
danielhanchen merged 5 commits into
mainfrom
ci-text-io-positional-encoding
Oct 13, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
ci-text-io-positional-encoding

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Problem

studio/backend/tests/test_text_io_encoding.py::test_text_io_names_its_encoding[gguf_variants.py] fails on main (2e718dc), seen in (Python 3.13, rest) on #13635:

gguf_variants.py:1278: read_text() without encoding

The line, added by #13565 (MLX precision folders), is:

config = json.loads((snapshot / folder / "config.json").read_text("utf-8"))

Test or product?

The product is right. Path.read_text(encoding=None, errors=None) takes the encoding as its first positional argument, so this read is UTF-8, not the locale default. The guard is wrong: for read_text / write_text it only recognised the encoding= keyword. Its own open() and Path.open() branches already accept a positional encoding, and so does the repo-level tests/test_source_read_encoding.py.

Fix

  • Argument 0 of read_text(encoding, errors) and argument 1 of write_text(data, encoding, ...) now count as naming the encoding.
  • A None or "locale" constant in that slot, or as encoding=, is still the locale default and stays flagged.
  • In an unbound call through a pathlib class (Path, PosixPath, PurePath, WindowsPath, pathlib.Path, or a from pathlib import ... as alias), the path comes first, so the encoding slot shifts by one. This matches _is_path_class in tests/test_source_read_encoding.py.
  • A starred argument at or before the slot hides the runtime position, so only a keyword encoding counts there.
  • Names bound by assignment, parameter defaults or subclassing are deliberately not treated as pathlib classes. Telling them apart needs the binding visible at each call site, and a module-wide guess flags valid calls on a same-named instance in another scope. A self-test case pins that.
  • test_the_guard_reads_a_positional_path_text_encoding pins every spelling above, in the style of the existing os.fdopen self-test.

Verification

main this PR
test_text_io_encoding.py 1 failed (gguf_variants.py) 804 passed
this PR's test file with the old keyword-only check restored gguf_variants.py and the new self-test fail
gguf_variants.py changed to read_text() (no encoding) gguf_variants.py is flagged again

#13565 reads an MLX config with read_text("utf-8"), which names its
encoding, but test_text_io_encoding only accepted the keyword and has
failed on main since. Treat argument 0 of read_text and argument 1 of
write_text as the encoding, as the open() and Path.open() branches
already do for theirs, and pin both spellings in a self-test.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T19:09:09.557078Z 0aed4e7 Manual request
🔒 Security Review ⚠️ Failed 2026-10-13T18:24:14.576147Z 47c6c3a PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 47c6c3a7cb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# Path.read_text(encoding, errors) and Path.write_text(data, encoding, ...) also take
# it positionally: read_text("utf-8") names its encoding as much as the keyword does.
positional = 0 if name == "read_text" else 1
if _has_keyword(node, "encoding") or len(node.args) > positional:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject positional locale-default encodings

When a call explicitly passes the locale default, such as path.read_text(None), path.read_text("locale"), or the corresponding second argument to write_text, this argument-count check now treats the call as safe even though Path still uses the platform-dependent encoding the guard is meant to prevent. Inspect the positional argument value and continue flagging the None and "locale" constants rather than accepting every supplied argument.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, fixed in 48843d2. A None or "locale" constant passed as the encoding, positionally or as encoding=, still counts as the locale default and stays flagged. read_text(None), read_text("locale"), read_text(encoding = "locale") and write_text("x", None) are now pinned in the self-test.

# Path.read_text(encoding, errors) and Path.write_text(data, encoding, ...) also take
# it positionally: read_text("utf-8") names its encoding as much as the keyword does.
positional = 0 if name == "read_text" else 1
if _has_keyword(node, "encoding") or len(node.args) > positional:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Account for unbound Path method calls

When Path methods are invoked in their valid unbound form, such as Path.read_text(path) or Path.write_text(path, data), the receiver occupies the first positional slot, but this check mistakes the path or data argument for an encoding and suppresses the offender. Detect Path/pathlib.Path receivers and shift the expected encoding position so these locale-dependent calls remain flagged.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 48843d2. When the receiver is Path or .Path, the encoding position shifts by one, so Path.read_text(p) and pathlib.Path.write_text(p, "x") are flagged, while Path.read_text(p, "utf-8") and pathlib.Path.write_text(p, "x", "utf-8") are not. All four are in the self-test.

None and "locale" passed as the encoding, by keyword or position, are
still the locale default, and Path.read_text(p) / Path.write_text(p, d)
carry the path first, so the encoding slot shifts by one. Pin both in
the self-test.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48843d2326

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +287 to +288
unbound = (isinstance(receiver, ast.Name) and receiver.id == "Path") or (
isinstance(receiver, ast.Attribute) and receiver.attr == "Path"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recognize aliased unbound Path methods

When Path is imported under an alias or a concrete class is used, such as from pathlib import Path as P; P.read_text(path) or PosixPath.write_text(path, data), this exact-name check leaves unbound false and mistakes the path/data argument for an encoding, so the locale-dependent call is not flagged. Fresh evidence beyond the earlier unbound-call cases is that the repository's analogous guard in tests/test_source_read_encoding.py::_is_path_class explicitly resolves aliases and concrete pathlib classes; this guard should likewise shift the encoding position for those valid unbound spellings.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, fixed in df9695a. The unbound check now covers Path, PosixPath, PurePath and WindowsPath, any name they are imported under from pathlib (from pathlib import Path as P), and qualified spellings like pathlib.Path. P.read_text(p) and PosixPath.write_text(p, "x") are flagged in the self-test, and P.read_text(p, "utf-8") is not.

from pathlib import Path as P; P.read_text(p) and PosixPath.write_text(p, d)
are unbound calls too, so shift the encoding slot for every pathlib
class and its import aliases, as test_source_read_encoding's
_is_path_class already does.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: df9695a086

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +289 to +292
if isinstance(node, ast.ImportFrom) and node.module == "pathlib":
for alias in node.names:
if alias.name in _PATH_CLASSES:
names.add(alias.asname or alias.name)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Track Path aliases created by assignment

Fresh evidence beyond the previously fixed import-alias cases is that valid aliases created by assignment are still missed: with P = Path or P = pathlib.Path, P.read_text(path) is treated as a bound call, so the path argument is mistaken for an encoding and the locale-default read is suppressed. This collector only follows ImportFrom aliases; it should also recognize simple assignments to known pathlib classes, as the subprocess alias collector already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f839a9. Simple assignments of a pathlib class (P = Path, P = pathlib.Path) are followed to a fixed point, so chains like Q = P count as well. Both cases are in the self-test.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: assignment aliases are no longer followed as of 0aed4e7. Doing it module-wide misread same-named instances in other scopes (see the lexical scope comment), and doing it properly needs per-call-site binding resolution, which is out of proportion for this guard.

Comment on lines +307 to +310
position = (0 if name == "read_text" else 1) + (1 if unbound else 0)
if len(node.args) <= position:
return False
return not _is_locale_default(node.args[position])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Account for expanded positional arguments

When positional values are supplied through *, len(node.args) counts AST expressions rather than the arguments produced at runtime. Consequently, p.write_text(*("x", "utf-8")) is reported even though it supplies an encoding, while p.read_text(*()) and Path.read_text(p, *()) are accepted even though they still use the locale default. Expand statically known tuple/list splats, or handle starred arguments explicitly instead of indexing the raw AST argument list.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f839a9. Rather than expanding splats, a starred argument at or before the encoding slot now means only a keyword encoding counts, since the runtime position cannot be known statically. That flags read_text(*()) and Path.read_text(p, *()), and leaves read_text(args, encoding = "utf-8") alone. It does flag write_text(("x", "utf-8")), but that is a conservative false positive for a spelling nothing in the tree uses.

…guard

P = Path (and chains of such assignments) is an alias too, and a starred
argument at or before the encoding slot hides its runtime position, so
only a keyword encoding counts there.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4f839a9184

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +294 to +297
assigns = [
(target.id, node.value)
for node in ast.walk(tree)
if isinstance(node, ast.Assign)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve Path aliases within their lexical scope

Collecting assignments with a module-wide ast.walk makes a local P = Path in one function classify every P.read_text(...) in the file as an unbound call, including calls in other functions and calls that occur before the assignment. For example, another function receiving a Path instance as P will have the valid P.read_text("utf-8") flagged because the encoding slot is shifted, while P.read_text(None, "ignore") is incorrectly accepted despite using the locale default. Alias resolution needs to respect the binding visible at each call site.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, the module-wide assignment collection was worse than not following it at all. In 0aed4e7 it is removed. Only pathlib import aliases (module-level by convention) and the four concrete classes count as unbound receivers, and a self-test case pins that a P parameter in another function is not treated as Path.

assigns = [
(target.id, node.value)
for node in ast.walk(tree)
if isinstance(node, ast.Assign)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include annotated assignments when resolving Path aliases

When a pathlib class alias is declared with an annotation, such as P: type = Path, this collector ignores it because it only accepts ast.Assign. The subsequent valid unbound call P.read_text(path) is then treated as a bound call whose path argument is an encoding, so a locale-dependent read escapes the guard. Handle ast.AnnAssign here as the subprocess alias collector already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not handling this one. Recognising this form correctly needs per-call-site binding and class-hierarchy resolution, and the keyword-only check this PR replaces did not catch it either. No Studio source uses it, so this PR stays scoped to the standard spellings: keyword or positional encoding, the locale-default constants, unbound calls through pathlib classes and their import aliases, and starred arguments.

Comment on lines +322 to +324
unbound = (isinstance(receiver, ast.Name) and receiver.id in path_classes) or (
isinstance(receiver, ast.Attribute) and receiver.attr in _PATH_CLASSES
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recognize pathlib subclasses in unbound calls

Fresh evidence beyond the previously fixed alias forms is an inherited pathlib subclass: class P(Path): pass; P.read_text(path) is a valid unbound call, but P is absent from path_classes, so the path argument is mistaken for a positional encoding and the locale-dependent read is not flagged. Collect class definitions whose bases resolve to known pathlib classes, including transitive subclasses, before deciding whether to shift the encoding slot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not handling this one. Recognising this form correctly needs per-call-site binding and class-hierarchy resolution, and the keyword-only check this PR replaces did not catch it either. No Studio source uses it, so this PR stays scoped to the standard spellings: keyword or positional encoding, the locale-default constants, unbound calls through pathlib classes and their import aliases, and starred arguments.

Comment on lines +294 to +297
assigns = [
(target.id, node.value)
for node in ast.walk(tree)
if isinstance(node, ast.Assign)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Follow Path aliases bound as parameter defaults

Fresh evidence beyond the previously handled import and assignment aliases is a helper that injects the class through a default, such as def load(path, cls=Path): cls.read_text(path). Because _path_class_names never inspects parameter defaults, cls is treated as an instance receiver and the path argument is mistaken for an encoding, allowing the locale-default read through. Collect positional and keyword-only defaults here as _subprocess_aliases already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not handling this one. Recognising this form correctly needs per-call-site binding and class-hierarchy resolution, and the keyword-only check this PR replaces did not catch it either. No Studio source uses it, so this PR stays scoped to the standard spellings: keyword or positional encoding, the locale-default constants, unbound calls through pathlib classes and their import aliases, and starred arguments.

Comment on lines +322 to +324
unbound = (isinstance(receiver, ast.Name) and receiver.id in path_classes) or (
isinstance(receiver, ast.Attribute) and receiver.attr in _PATH_CLASSES
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply discovered Path aliases to qualified receivers

For a class or namespace alias such as class Paths: P = Path, the collector adds P to path_classes, but Paths.P.read_text(path) is still not recognized as unbound because attribute receivers are checked only against the four hard-coded class names. The path is consequently accepted as a positional encoding and the locale-dependent read is missed; compare receiver.attr with the resolved alias set as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not handling this one. Recognising this form correctly needs per-call-site binding and class-hierarchy resolution, and the keyword-only check this PR replaces did not catch it either. No Studio source uses it, so this PR stays scoped to the standard spellings: keyword or positional encoding, the locale-default constants, unbound calls through pathlib classes and their import aliases, and starred arguments.

Collecting P = Path across the whole module ignored scope, so a P
parameter holding a Path instance in another function had its valid
read_text("utf-8") flagged. Follow only pathlib import aliases and pin
the same-named-instance case in the self-test.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 0aed4e72dd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant