- Format Python Code in Visual Studio Code (VS Code)
- Option 3: Using Palette Command:
- Video Related to this Article will Load Here:
- Facing issues? Have Questions? Post them here! I am happy to answer!
- Automatically reformat Python code in Visual Studio
- Define formatting rules
- Apply format to selection or file
- Spacing examples
- Statement options
- Wrapping options
- Format comment text
- Feedback
- Quick guide to Python formatting in VS Code
- Prettier does not work with Python
- Override default formatter
Format Python Code in Visual Studio Code (VS Code)
Note the first time you use the formatting shortcut you will get a VS Code Alert saying «Formatter autopep8 is not installed. Install?» do say YES or you can install it using pip command manually.
/opt/homebrew/bin/python3 -m pip install -U autopep8 Collecting autopep8 Downloading autopep8-1.7.0-py2.py3-none-any.whl (45 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 45.6/45.6 kB 1.1 MB/s eta 0:00:00 Collecting pycodestyle>=2.9.1 Downloading pycodestyle-2.9.1-py2.py3-none-any.whl (41 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 41.5/41.5 kB 2.3 MB/s eta 0:00:00 Collecting toml Downloading toml-0.10.2-py2.py3-none-any.whl (16 kB) Installing collected packages: toml, pycodestyle, autopep8 Successfully installed autopep8-1.7.0 pycodestyle-2.9.1 toml-0.10.2
Be on your Python code file and do a right-click and select: Format Document
You can also select a section of your code and format it by selecting «Format Section»
Option 3: Using Palette Command:
Another way is to use the Palette Command,
For Windows: Control + Shift + P
For Mac: Command + Shift + P
Now search for Format Document and select to format.
Do share in the comments if you know of any other ways or tricks to format Python code in VS Code!
Video Related to this Article will Load Here:
Facing issues? Have Questions? Post them here! I am happy to answer!
- 26: How to set Environment Variables using Python
- Python Sleep Function/Method Code Example
- Tkinter — add x and y padding to label text
- Define an Infinite Number in Python
- How to comment out a block of code in Python
- Jupyter Notebook: 404 : Not Found — You are requesting a page that does not exist!
- How to know the Python Version of Jupyter Notebook
- Fix: Jupyter Notebook says Not Trusted
- Change label (text) color in tkinter
- Python: Create CSV file from a List Values
- How to Save Jupyter Notebook as PDF
- Python: How to Plot a Histogram using Matplotlib and data as list
- What is Markdown in Jupyter Notebook with Examples
- How to write a binary file in Python
- Python: How to rename Index Names Pandas DataFrame
- Python Comments Multiple Lines
- How to get the Execution Time of A Python Program
- How to delete a dir or folder using Python code
- Take input argument from command line in Python Programming
- 3 Ways to convert bytes to String in Python
- [Python] Fix: TypeError: NoneType object is not subscriptable
- Advanced print() Function Tutorial and Techniques for Python Developers
- Fix: error: invalid command bdist_wheel — Python
- GitPython: How to check out a Branch
- Python — Convert float to String
Know the Author: With a Masters Degree in Computer Science, Rakesh is a highly experienced professional in the field. With over 18 years of practical expertise, he specializes in programming languages such as Java, Python, Sharepoint, PHP, and Rust. He is dedicated to delivering high-quality solutions and providing valuable insights to meet the unique challenges of the digital landscape. rakesh@code2care.org is where you can reach him out.
We keep our articles short so the focus remains on providing effective tech solutions while promoting healthier screen habits and enhancing overall well-being. 📝 💡 🌱 By reducing screen time, we contribute to a greener future, reducing carbon emissions and fostering digital well-being. 🌍 🌿 🔋
We are celebrating the 10th years of Code2care! Thank you for all your support!
We strongly support Gender Equality & Diversity — #BlackLivesMatters
Automatically reformat Python code in Visual Studio
Applies to: Visual Studio
Visual Studio for Mac
Visual Studio Code
Visual Studio lets you quickly reformat code to match pre-configured formatting options.
Define formatting rules
You can set your formatting options through the menus Tools > Options > Text Editor > Python > Formatting and its nested tabs. Formatting options by default are set to match a superset of the PEP 8 style guide. The General tab determines when formatting is applied; settings for the other three tabs are described in this article.
You need to select Show all settings for these options to appear:
Python support in Visual Studio also adds the useful Fill Comment Paragraph command to the Edit > Advanced menu as described in a later section.
Apply format to selection or file
Spacing examples
Spacing controls where spaces are inserted or removed around various language constructs. Each option has three possible values:
- Checked: ensures the spacing is applied.
- Cleared: removes any spacing.
- Indeterminate: leaves original formatting in place.
Examples for the various options are provided in the following tables:
Class definitions option | Checked | Cleared |
---|---|---|
Insert space between a class declaration’s name and bases list | class X (object): pass | class X(object): pass |
Insert space within bases list parentheses | class X( object ): pass | class X(object): pass |
Insert space within empty bases list parentheses | class X( ): pass | class X(): pass |
Function definitions option | Checked | Cleared |
---|---|---|
Insert space between a function declaration’s name and parameter list | def X (): pass | def X(): pass |
Insert space within parameter list parentheses | def X( a, b ): pass | def X(a, b): pass |
Insert space within empty parameter list parentheses | def X( ): pass | def X(): pass |
Insert spaces around ‘=’ in default parameter values | includes X(a = 42): pass | includes X(a=42): pass |
Insert space before and after return annotation operators | includes X() -> 42: pass | includes X()->42: pass |
Operators option | Checked | Cleared |
---|---|---|
Insert spaces around binary operators | a + b | a+b |
Insert spaces around assignments | a = b | a=b |
Expression spacing option | Checked | Cleared |
---|---|---|
Insert space between a function call’s name and argument list | X () | X() |
Insert space within empty argument list parentheses | X( ) | X() |
Insert space within argument list parentheses | X( a, b ) | X(a, b) |
Insert space within parentheses of expression | ( a ) | (a) |
Insert space within empty tuple parentheses | ( ) | () |
Insert space within tuple parentheses | ( a, b ) | (a, b) |
Insert space within empty square brackets | [ ] | [] |
Insert spaces within square brackets of lists | [ a, b ] | [a, b] |
Insert space before open square bracket | x [i] | x[i] |
Insert space within square brackets | x[ i ] | x[i] |
Statement options
The Statements options control automatic rewriting of various statements into more Pythonic forms.
Option | Before formatting | After formatting |
---|---|---|
Place imported modules on new line | import sys, pickle | import sys import pickle |
Remove unnecessary semicolons | x = 42; | x = 42 |
Place multiple statements on new lines | x = 42; y = 100 | x = 42 y = 100 |
Wrapping options
Wrapping lets you set the Maximum comment width (default is 80). If the Wrap comments that are too wide option is set, Visual Studio reformats comments to not exceed that maximum width.
# Wrapped to 40 columns # There should be one-- and preferably # only one --obvious way to do it.
# Not-wrapped: # There should be one-- and preferably only one --obvious way to do it.
Format comment text
Edit > Advanced > Fill Comment Paragraph (Ctrl+E > P) reflows and formats comment text, combining short lines together and breaking up long ones.
Reformat | Example 1 |
---|---|
Before | # This is a very long long long long long long long long long long long long long long long long long long long comment |
After | # This is a very long long long long long long long long long long long long # long long long long long long long comment |
Reformat | Example 2 |
---|---|
Before | # foo # bar # baz |
After | # foo bar baz |
Feedback
Submit and view feedback for
Quick guide to Python formatting in VS Code
You’ve followed Microsoft’s tutorial on setting up Python in VS Code but formatting is just not working? It might be that other extensions are interfering with your Python formatter. If you use VS Code mostly for web development, you most likely also use Prettier for formatting. I’m talking about Prettier as an extension, not as a package. Check if you have the following configuration in your settings: (Open VS Code, hit Ctrl + Shift + P on Windows / Cmd + Shift + P on MacOS to open the Command Palette and search for «Settings», check both «Workspace» and «User» settings).
Prettier does not work with Python
"editor.defaultFormatter": "esbenp.prettier-vscode"
If you find this config in your settings, you’ve found the reason why autopep8 , black or yapf are not working — The above configuration will choose Prettier to format Python, which is not supported. In your settings, make sure you override the default formatter for python like so:
"[python]": "editor.defaultFormatter": null >
And don’t forget to install and select the actual formatter that you want (just like in the official docs).
"python.formatting.provider": "black", "python.formatting.blackArgs": ["--line-length", "120"]
Override default formatter
You can either overwrite editor.defaultFormatter just for your workspace or globally for your user. Also, it doesn’t matter whether you’re using a global Python installation or a virtual environment. I prefer applying this configuration to my user settings — this way, I can easily start a Python project and will get formatting out of the box based on my user settings. No need to create dedicated workspace settings for every single project and override the formatter over and over. Here’s the relevant config from my settings:
"editor.defaultFormatter": "esbenp.prettier-vscode", "[python]": "editor.defaultFormatter": null >, "python.formatting.blackArgs": ["--line-length", "120"], "python.formatting.provider": "black", >
Originally posted on my personal website and blog, eric.film. Preview picture by @fidpad on unsplash.