1

How to remove the line breaks that's added in the formatting when saving the code in VSCode

For example:

If I have an expression with multiple validations:

if True == True or False == True or False == False:

It is being formatted as:

if (True == True
or False == True
or False == False)

This complicates readability. How can I reformat it to look like the first example?

7
  • 5
    Turn off VSCode's automatic reformatting. This is not something that Python does. Commented Jun 21, 2024 at 16:44
  • but if i do it, the code will be reformatted? Commented Jun 21, 2024 at 16:46
  • No, that's the whole point. I don't use VSCode, so I can't tell you precisely what option to change. But there should be a way to turn off things like this. Commented Jun 21, 2024 at 16:49
  • 1
    There may also be a list of specific formatting options, and you can just disable this one. Commented Jun 21, 2024 at 16:50
  • 1
    @MarkRansom, OP, et al: there's a checkbox for "Format on Save" in the Settings. It's not language specific, by the look of it. You can find it by typing that right into the "Search settings" field once you open Settings. Commented Jun 21, 2024 at 17:10

2 Answers 2

1

You can use the shortcut Ctrl+, to open the settings. Input format on save and deselect the Editor:Format On Save option. This disables the use of code formatting when saving documents globally. This preserves the format of the code you wrote it.enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

First check to see which formatter VSCode is using to format your code. In most cases (I tried Black and Ruff), you can disable the formatting of a specific piece of code by wrapping it inside the below block:

# fmt: off
lst = [1, 2, 3,
       4, 5, 6,
       7, 8 ,9]
# fmt: on

Without that comment, it would put them in single line.

I guess most formatters will respect that comment.

1 Comment

autopep8 also respects that comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.