skip to Main Content

I am using VS code to write python code.

When writing functions I get:
enter image description here

What I would like to have when I hit return after every variable of the method is:
enter image description here

But after hitting return after the first argument the next line starts just under "def".

After looking for solutions in internet I read somewhere that adding this to settings.json would solve it:

"editor.autoIndent": true,
"editor.indentAfterOpenBracket": "control"
}

But this is not the case and the behavior remains the same.

How and what should be added in settings.json to get this behavior.

3

Answers


  1. I use balck, you can run command pip install black and add the following codes to your settings.json:

      "python.formatting.provider": "black",
    

    You can read black document for more details.

    enter image description here

    Login or Signup to reply.
  2. To change the indentation of Python functions in VS Code, you can use YAPF, you can install the "YAPF Formatter" extension and then configure it to format your code using the desired indentation style. Here are the steps to do this:

    • Install the "YAPF Formatter" extension in VS Code by searching for it in the Extensions marketplace or by visiting the following link: https://marketplace.visualstudio.com/items?itemName=mr-konn.yapf

    • Open the settings.json file in VS Code by going to File > Preferences > Settings or by pressing Ctrl + ,

    • In the settings.json file, add the following lines to configure YAPF to use the desired indentation style:

        "python.formatting.yapfArgs": [
            "--style={based_on_style: pep8, indent_width: 4}"
        ],
    
    • Save the settings.json file and then you can format your python file by going to Edit > Format Document or by using the shortcut key Ctrl+Shift+I

    Note: You can also configure YAPF to use different indentation style other than the one mentioned in the above example by modifying the indent_width and based_on_style fields in the yapfArgs settings

    Login or Signup to reply.
  3. I don’t think there is such setting in VSCode. To do that you need to use a formatter. You can configure your VSCode to use Black.

    It doesn’t matter how long the length of the line is, if you put a , at the end of your parameters, it puts them in separate lines:

    # in
    def short(a, b,):
        pass
    
    # out
    def short(
        a,
        b,
    ):
        pass
    

    But the parenthesis are problem here(unless you don’t care). Black doesn’t put them along parameters like how you showed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search