Skip to content

Fix extract method with f-strings containing "#" (supersedes #808) - #988

Open
mcepl wants to merge 5 commits into
masterfrom
fstring-hash-807
Open

mcepl wants to merge 5 commits into
masterfrom
fstring-hash-807

Conversation

@mcepl

@mcepl mcepl commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

This takes over #808 by @rlbr, which has been waiting for almost two years. The two original commits are kept unchanged, with their authorship, and rebased onto #985. A follow-up commit addresses the review comments.

The bug (#807): CodeTemplate._find_names() skips ${name} placeholders inside comments and strings. It never recognised f-strings, so the # in f"#{h}" was taken for the start of a comment. That hid the placeholder, left ${h} in the generated code, and extract method failed with f-string: invalid syntax.

The original fix (#808) matched f-strings with a regular expression and then collected the names inside them.

Follow-up commit:

  • A regular expression can't find the end of an f-string since Python 3.12 (PEP 701), because nested strings may use the same quotes. f"{d["#"]}${h}" therefore regressed compared with master. The regular expression is replaced by a small scanner that follows replacement fields, nested (f-)strings, format specs (where quotes are literal, e.g. {x:'^10}) and {{/}} escapes.
  • Names are only searched for inside the f-string that was found, instead of rescanning the whole template once per f-string.
  • The prefix needs a word boundary, so elif"..." is no longer taken for an f-string.
  • The duplicated name bookkeeping is moved into _add_name(), and the redundant groupdict() checks are dropped.
  • New unit tests for CodeTemplate, plus extract-method tests for the exact case in the issue (extracting only the expression) and for nested quotes (3.12+).
  • New changelog fragment: changelog.d/807.md.

t-strings (t"…") still aren't handled, as before. The plain-string pattern swallows them, so placeholders inside them are not found. That is now tracked in #989.

This PR is stacked on #985 because it uses changelog.d/. Please merge #985 first.

Fixes #807
Supersedes #808

Checklist (delete if not relevant):

  • I have added a changelog fragment
  • I have added tests covering the change

Nearly every pull request conflicted on the top of CHANGELOG.md,
because all of them appended to the same "Upcoming release"
section. Following a much simplified version of CPython's
blurb/NEWS.d workflow, each PR now adds a small Markdown file
changelog.d/<issue>.md with its entry, so parallel PRs never
touch the same file.

The new bin/news script (plain POSIX sh, so it works on Linux,
the BSDs and macOS) creates a fragment in $VISUAL/$EDITOR from a
template encouraging longer, explanatory entries (`bin/news 123`),
previews the pending release section (`bin/news preview`), and
folds the fragments, sorted by number, into a new "# Release
<version>" section of CHANGELOG.md (`bin/news collect`). A new
portable top-level Makefile wraps it as `make news N=123`,
`make changelog-preview`, `make changelog` and `make release`,
the last of which also builds the documentation via
docs/Makefile; that gains an explicit `html` rule, as its
Sphinx-generated catch-all pattern rule is GNU make only. The
news target passes N and TEXT to bin/news through the
environment ("$$N", "$$TEXT"), so Markdown backticks and quotes
in an entry reach the script literally instead of being
re-parsed by the shell.

The pending entry for the #223 regression tests, previously in
the "Upcoming release" section, has been moved to
changelog.d/223.md, and the PR template, contributing and
release-process docs updated.
@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.86992% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.44%. Comparing base (d5a8021) to head (c88c68d).

Files with missing lines Patch % Lines
rope/refactor/similarfinder.py 87.50% 10 Missing ⚠️
Additional details and impacted files
@@                     Coverage Diff                      @@
##           changelog-news-fragments     #988      +/-   ##
============================================================
- Coverage                     95.46%   95.44%   -0.02%     
============================================================
  Files                           134      134              
  Lines                         26946    27055     +109     
============================================================
+ Hits                          25723    25822      +99     
- Misses                         1223     1233      +10     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

mcepl and others added 4 commits November 30, 2026 12:17
As @lieryan pointed out in the review, requiring a POSIX shell
(and make) just to write a changelog entry would raise the
barrier for contributors on Windows, who so far only needed make
for building the documentation, and even there Sphinx provides
make.bat.

Replace the sh script with bin/news.py, which uses only the
standard library and keeps the same commands (add, preview,
collect). It looks for an editor in $VISUAL, $EDITOR and git's
core.editor, falling back to Notepad on Windows and vi elsewhere,
writes LF line endings everywhere, and numbers duplicate
fragments 1234-2.md, 1234-3.md, … instead of using a timestamp.

The contributor documentation now leads with simply creating
changelog.d/<N>.md in any editor, offers `python bin/news.py <N>`
as a helper, and mentions the make targets only as a shortcut;
these remain for the release manager and call the script via
$(PYTHON). The #985 fragment is expanded accordingly.
The previous fix matched f-strings with a regular expression and
then rescanned the whole template for each one.  A regular
expression cannot find the end of an f-string since Python 3.12
allows nested strings using the same quotes (PEP 701), so
templates like f"{d["#"]}${h}" regressed: the inner quote ended
the match and the following `#` hid the rest of the line again.

Replace it with a small scanner which follows replacement fields,
nested (f-)strings, format specifications and `{{`/`}}` escapes,
and only looks for names within the f-string found.  The prefix
pattern now requires a word boundary, so `elif"..."` is no longer
mistaken for an f-string.  The name bookkeeping is factored into
_add_name().  Add unit tests for CodeTemplate, a test extracting
just the f-string expression as in the original report, and a
changelog fragment.

Fixes: #807
@lieryan

lieryan commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

We used to use regex to find the end of strings because ast nodes didn't used to contain end_pos/end_col_offset. And that used to work fine because string syntax used to be very simple in Python 2.

But now that the ast nodes tracks their end position and Python grammar is no longer really LL(1), couldn't we just ast.parse() (or alternatively tokenize.generate_tokens, which would be more robust against files with invalid syntax) and use ASTLinesAdapter to find end positions of constructs rather than writing bits and pieces of our own parsing?

Base automatically changed from changelog-news-fragments to master December 1, 2026 22:17

This branch has not been deployed

No deployments
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.

3 participants