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

Convert %d if the input is a explicit int conversion #202

Merged
merged 4 commits into from
Feb 2, 2025
Merged
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
17 changes: 15 additions & 2 deletions src/flynt/transform/percent_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,20 @@ def is_percent_stringify(node: ast.BinOp) -> bool:
)


def _is_builtin_int_call(val: ast.AST) -> bool:
return _is_int_call(val) or _is_len_call(val)


def _is_int_call(val: ast.AST) -> bool:
return (
isinstance(val, ast.Call)
and isinstance(val.func, ast.Name)
and val.func.id == "int"
)


def _is_len_call(val: ast.AST) -> bool:
# assume built-in len always returns int
return (
isinstance(val, ast.Call)
and isinstance(val.func, ast.Name)
Expand Down Expand Up @@ -65,8 +78,8 @@ def formatted_value(
)
fmt_spec = translate_conversion_types.get(fmt_spec, fmt_spec)
if fmt_spec == "d":
# assume built-in len always returns int
if not _is_len_call(val):
# test if is a built-in that returns int
if not _is_builtin_int_call(val):
if not aggressive:
raise ConversionRefused(
"Skipping %d formatting - fstrings behave differently from % formatting.",
Expand Down
9 changes: 9 additions & 0 deletions test/test_edits.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ def test_string_specific_len(state: State):
assert s_out == s_expected


def test_dont_wrap_int(state: State):
s_in = """print('Int cast %d' % int(18.81))"""
s_expected = """print(f'Int cast {int(18.81)}')"""

state.aggressive = True
s_out, count = code_editor.fstringify_code_by_line(s_in, state)
assert s_out == s_expected


def test_dont_wrap_len(state: State):
s_in = """print('List length %d' % len(sys.argv))"""
s_expected = """print(f'List length {len(sys.argv)}')"""
Expand Down
Loading