Code Formatting in Visual Studio Code — My Essential Python Snippet
A small piece of code to reuse every time you spin up a new Python project
Let’s get straight to the point.
In your VSCode project root folder, find the settings.json
file. If you’re working within a virtual environment, this will automatically appear in your project.
Make sure you have the python.pythonPath
argument set correctly first.
Now, install black and isort packages via pip:
pip install black isort
Finally, append this snippet to the json:
"python.formatting.provider": "black","editor.formatOnSave" : true,"python.formatting.blackArgs": ["--line-length=119"],"python.sortImports.args": ["--profile=black",],"[python]": {"editor.codeActionsOnSave": {"source.organizeImports": true}},
And that’s it! Now, you can simply go ahead and continue working normally, when you save a python file, black will auto restructure your file.
Cool, isn’t it? 😎
In case you want to just run formatting over all the files in a big project folder, just run:
black folder_name/
and it will find all .py files within the folder recursively and format them!
I post various tidbits of my Data Science learning on my Twitter. Follow me to never miss them.