Skip to content

Extract method: placeholders inside t-strings are not substituted (CodeTemplate treats t"…" as a plain string) #989

Backlog

Description

@mcepl

Describe the bug

similarfinder.CodeTemplate._find_names() collects ${name} placeholders but skips those inside comments and plain strings. Since #988 (fix for #807) f-strings are scanned properly, but template strings (PEP 750, Python 3.14) are still treated as plain strings. codeanalyze.get_string_pattern() uses the prefix (?<![fF])(\b[uUbB]?[rR]?)?, so the t is not excluded; the quotes that follow it match as an ordinary string and swallow every placeholder inside:

>>> from rope.refactor.similarfinder import CodeTemplate
>>> CodeTemplate('(f"{${h}}")').names
{'h': [(4, 8)]}
>>> CodeTemplate('(t"{${h}}")').names
{}

This differs from #807: there a # hid the placeholder, but here a t-string hides its placeholders even without any #.

Where it matters

When extracting an expression, _ExtractMethodParts.get_body_pattern() turns the selection into a template such as (t"{${h}}") ((f"#{${h}}") for the f-string case in #807). With the placeholder not found, ${h} stays in the code that rope later parses, so extract method on code containing a t-string with replacement fields will most likely fail with a syntax error, as it did for #807. I couldn't confirm this end to end because I don't have Python 3.14 to hand; the CodeTemplate behaviour above is reproducible on any Python version.

To Reproduce (Python 3.14)

def main():
    h = 1
    g = t"{h}"

Extract method on t"{h}" (or on the whole g = … line).

Expected

def main():
    h = 1
    g = extracted(h)

def extracted(h):
    return t"{h}"

Suggested fix

In CodeTemplate, treat the t/T prefixes (alone or with r/R) like f. The scanner from #988 already treats nested t-strings as formatted, so only the prefix regex (_fstring_start_pattern) and the plain-string pattern need changing. get_string_pattern() is also used by rope/refactor/inline.py, so excluding t there ((?<![fFtT])) needs checking against inline as well. simplify.real_code already handles both prefixes since #913/#915.

Related: #807, #988, #913.

Activity

  1. added
    bug
    on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions