Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle the edge case where an f-string looks like f"#{some_var}" #808

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 39 additions & 13 deletions rope/refactor/similarfinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,10 +269,26 @@ def get_region(self):


class CodeTemplate:
_dollar_name_pattern = r"(?P<name>\$\{[^\s\$\}]*\})"

def __init__(self, template):
self.template = template
self._find_names()

@classmethod
def _get_pattern(cls):
if cls._match_pattern is None:
pattern = "|".join(
(
codeanalyze.get_comment_pattern(),
codeanalyze.get_string_pattern(),
f"(?P<fstring>{codeanalyze.get_formatted_string_pattern()})",
cls._dollar_name_pattern,
)
)
cls._match_pattern = re.compile(pattern)
return cls._match_pattern

def _find_names(self):
self.names = {}
for match in CodeTemplate._get_pattern().finditer(self.template):
Expand All @@ -283,6 +299,29 @@ def _find_names(self):
self.names[name] = []
self.names[name].append((start, end))

elif "fstring" in match.groupdict() and match.group("fstring") is not None:
self._fstring_case(match)

def _fstring_case(self, fstring_match: re.Match):
"""Needed because CodeTemplate._match_pattern short circuits
as soon as it sees a '#', even if that '#' is inside a f-string
that has a ${variable}."""

string_start, string_end = fstring_match.span("fstring")

for match in re.finditer(self._dollar_name_pattern, self.template):
if match.start("name") < string_start:
continue

if match.end("name") > string_end:
break

start, end = match.span("name")
name = self.template[start + 2 : end - 1]
if name not in self.names:
self.names[name] = []
self.names[name].append((start, end))

def get_names(self):
return self.names.keys()

Expand All @@ -298,19 +337,6 @@ def substitute(self, mapping):

_match_pattern = None

@classmethod
def _get_pattern(cls):
if cls._match_pattern is None:
pattern = (
codeanalyze.get_comment_pattern()
+ "|"
+ codeanalyze.get_string_pattern()
+ "|"
+ r"(?P<name>\$\{[^\s\$\}]*\})"
)
cls._match_pattern = re.compile(pattern)
return cls._match_pattern


class _RopeVariable:
"""Transform and identify rope inserted wildcards"""
Expand Down
22 changes: 22 additions & 0 deletions ropetest/refactor/extracttest.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,28 @@ def extracted():
""")
self.assertEqual(expected, refactored)

def test_extract_function_with_fstring(self):
code = dedent("""\
def main():
h = 1
g = f"#{h}"
print(g)
""")
start, end = self._convert_line_range_to_offset(code, 3, 3)
refactored = self.do_extract_method(code, start, end, "extracted")

expected = dedent("""\
def main():
h = 1
g = extracted(h)
print(g)

def extracted(h):
g = f"#{h}"
return g
""")
self.assertEqual(expected, refactored)

def test_extract_function_containing_dict_generalized_unpacking(self):
code = dedent("""\
def a_func(dict1):
Expand Down
Loading