sourcery-ai / sourcery

Instant AI code reviews
https://sourcery.ai
MIT License
1.51k stars 65 forks source link

Sourcery producing not working code when formatting strings #325

Closed PipeKnight closed 1 year ago

PipeKnight commented 1 year ago

Checklist

Description

Sourcery suggested me to change some lines of code and after changing, the code is not working. Sourcery produces wrong syntax.

Code snippet that reproduces issue

Initial code:

assert (
     response.text
     == '{"detail":"ValueError(\'You need to pass on the same number of answers'
    " and options as in the question.You pass number of answers ="
    f" {(valid_number_answers + 1)} and numbers of questions_options is"
    f" {valid_number_answers}') in question"
    f" {question_matching_question_id}\"{'}'}"
)

Sourcery suggestion:

Sourcery - Simplify unnecessary nesting, casting and constant values in f-strings sourcery(refactoring:simplify-fstring-formatting)

Result of refactoring:

assert (
        response.text
        == f"""{"detail":"ValueError(\'You need to pass on the same number of answers and options as in the question.You pass number of answers = {valid_number_answers + 1} and numbers of questions_options is {valid_number_answers}') in question {question_matching_question_id}\"}"""
    )

Debug Information

Using VSCode, Python 3.11.2 and Sourcery v1.0.4

Sourcery Version: v1.0.4 VSCode extension

Operating system and Version: macOS 13.2 (22D49)

bm424 commented 1 year ago

Hi @PipeKnight, thanks for sharing this. I've been able to reproduce the issue, and it looks like this is to do with our handling of the {} characters, which should be changed to the escaped versions {{}} in the f-string. I've added this to our backlog and it should be fixed in an upcoming release.

In the meantime, if you adjust the refactored version to

assert (
        response.text
        == f"""{{"detail":"ValueError(\'You need to pass on the same number of answers and options as in the question.You pass number of answers = {valid_number_answers + 1} and numbers of questions_options is {valid_number_answers}') in question {question_matching_question_id}\"}}"""
    )

that should allow the code to work properly again.

Karim-53 commented 1 year ago

There is a similar issue when using f string and multiline string:

x = f'''
text: {set(item for item in d)}
'''

will become

x = f'''
text: {{item for item in d}}
'''

why sourcery doesn't apply one of code checker libraries (mypy?) on the proposed change, and propose it only if there is no new error happening?

bm424 commented 1 year ago

The original refactoring will no longer be suggested as of sourcery version 1.0.9.

@Karim-53 I have migrated your comment to a new issue (see above)