简体   繁体   中英

change indentation in VS code for python functions

I am using VS code to write python code.

When writing functions I get: 在此处输入图像描述

What I would like to have when I hit return after every variable of the method is: 在此处输入图像描述

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

After looking for solutions in inte.net 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.

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

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.

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.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM