Automatically reformat Python code in Visual Studio
Visual Studio lets you quickly reformat code to match specific formatter standards. In this article, you explore how to access and enable formatting features.
Choose a formatter
You can set your source code formatter through Tools > Options > Text Editor > Python > Formatting. Python Tools in Visual Studio support source code formatting with autopep8, Black formatter, and yapf.
Python support in Visual Studio also adds the Fill Comment Paragraph command to the Edit > Advanced menu as described in a later section.
Apply format to selection or file
You can apply formatting settings to all content in a file or only to a specific selection.
To format a selection, select Edit > Advanced > Format Selection.
To format the whole file, select Edit > Advanced > Format Document.
Word wrap
You can enable word wrapping in Tools > Options > Text Editor > Python > General. In the Settings section, select the Word wrap checkbox.
Format comment text
The Edit > Advanced > Fill Comment Paragraph option reflows and formats comment text.
Reformat long lines
Use the feature to break up long lines of text, as shown in this example:
# This is a very long long long long long long long long long long long long long long long long long long long comment
The text is reformatted as multiple lines:
# This is a very long long long long long long long long long long long long
# long long long long long long long comment
Combine short lines
Use the feature to combine short lines of text, as shown in this example:
# Short line of text
# more text
# text
The text is reformatted into a single line:
# Short line of text more text text