Skip to content

Commit

Permalink
Avoid partial conversions on % with dict r.h.s. - fixes #89
Browse files Browse the repository at this point in the history
  • Loading branch information
ikkamens committed Mar 27, 2021
1 parent 4506c78 commit fc35201
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/flynt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
from old "%-formatted" and .format(...) strings into Python 3.6+'s f-strings.
Learn more about f-strings at https://www.python.org/dev/peps/pep-0498/"""

__version__ = "0.62"
__version__ = "0.63"

from flynt.cli import main
6 changes: 6 additions & 0 deletions src/flynt/transform/percent_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

PREFIX_GROUP = "[0-9]*[.]?[0-9]*"

ANY_DICT = re.compile(r"(?<!%)%\([^)]+?\)")
DICT_PATTERN = re.compile(rf"(%\([^)]+\){PREFIX_GROUP}{FORMAT_GROUP})")
SPLIT_DICT_PATTERN = re.compile(rf"%\(([^)]+)\)({PREFIX_GROUP}){FORMAT_GROUP_MATCH}")
VAR_KEY_PATTERN = re.compile(
Expand Down Expand Up @@ -68,6 +69,11 @@ def transform_dict(node):

format_str = node.left.s
matches = DICT_PATTERN.findall(format_str)
if len(matches) != len(ANY_DICT.findall(format_str)):
raise FlyntException(
"Some locations have unknown format modifiers."
)

spec = []
for idx, m in enumerate(matches):
_, var_key, prefix, fmt_str, _ = SPLIT_DICT_PATTERN.split(m)
Expand Down
9 changes: 9 additions & 0 deletions test/test_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,3 +454,12 @@ def test_kv_loop():

out, count = process.fstringify_code_by_line(s_in)
assert out == expected


def test_unknown_mod_percend_dictionary():
"""Unknown modifier must not result in partial conversion!"""

s_in = """\"%(a)-6d %(a)s" % d"""

out, count = process.fstringify_code_by_line(s_in)
assert out == s_in

0 comments on commit fc35201

Please sign in to comment.