Skip to content

UP012 autofix error when encode() call is split to multiple lines #3797

@jvtm

Description

@jvtm

UP012 fix / diff mode fails to remove unnecessary utf-8 (default) encoding parameter when the function call is split to multiple lines.

def ruff_up012_fix_buggy(a: int, b: str) -> bytes:
    return f"{a=} {b=}".encode(
        "utf-8",
    )

Using check --show-source:

$ ruff check --isolated --extend-select UP up012_fix_bug.py --show-source
up012_fix_bug.py:2:12: UP012 [*] Unnecessary call to `encode` as UTF-8
  |
2 |       return f"{a=} {b=}".encode(
  |  ____________^
3 | |         "utf-8",
4 | |     )
  | |_____^ UP012
  |
  = help: Remove unnecessary `encode`

Found 1 error.
[*] 1 potentially fixable with the --fix option.

Trying to --diff:

$ ruff check --isolated --extend-select UP up012_fix_bug.py --diff

error: Autofix introduced a syntax error. Reverting all changes.

This indicates a bug in `ruff`. If you could open an issue at: ...

I'm pretty sure ruff is leaving the trailing comma behind, leading to a syntax error.

Looks like using pyupgrade collapses the call to a single line.

When the original statement is on a single line everything works.

Note that the help message "Remove unnecessary encode" is misleading. This case is about removing the unnecessary utf-8 parameter to encode(), as that is the same as the default value. In case of f-strings there's no direct "bytes" variant (regular strings could be written as b"foobar" directly).

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions