Python setup in VS Code with Poetry & Black formatter
Python setup in VS Code with Poetry & Black formatter
Written on
May 25, 2020
Here's my simple workflow when working with Python scripts, using VS Code with the official Python extension for editing, Python's built-in venv for managing the virtual environment, Poetry for dependencies management, and Black to automatically format my code.
Grab a copy of the excellent Visual Studio Code if you haven't already!
In the editor, press Ctrl+Shift+X to open the extension marketplace and search and install the Python extension by Microsoft.
Install Poetry system-wide
Poetry allows you to quickly create a Python boilerplate project with Poetry create <project_name>. Alternatively, if you prefer to use your own folder structure or already have an existing project, run poetry init inside your project.
With your project opened in VS Code, open a new terminal by pressing Ctrl+Shift+' and run python -m venv .env to create a virtual environment. VS Code will ask you if you want to set it up as the project's environment - say yes. This setting will be saved inside the .vscode\settings.json file - you usually want to add this to your .gitignore
Close the terminal window. Now every time you open a new terminal with any .py file open in the editor, VS Code will automatically activated the virtual environment in that shell. Try that now!
Make sure you're in a virtual environment-activated shell by following the step above, then run poetry add --dev black to install the Black formatter as a development dependency
All set! You can format the existing document by pressing Shift+Alt+F, or enable format on save from VS Code's settings. Make sure that Black is selected as Python's formatting provider in the extension settings.
By default, Black formats code with a maximum line length of 88 characters. You might want to enable a ruler in your settings.json file just for python files to visualize this. If you want, you can modify the maximum line length by adding the --line-length parameter to the list of Black arguments. Press Ctrl+Shift+P to open the command palette and search and select "Preferences: Opens Settings (Json)". Then add your proffered options:
"python.formatting.provider": "black", "python.formatting.blackArgs": [ "--line-length", "90" ], "[python]": { "editor.rulers": [90] },
Thanks to poetry, the project's dependencies are tracked nicely in the pyproject.toml file. When distributing your script, it might be a good idea to instruct your users to use poetry install --no-dev when installing dependencies to skip over the development packages. On top of that, you might want to generate a requirements.txt file anyway so that users without poetry can install the dependencies for your project as well. You can do this by running poetry export -f requirements.txt > requirements.txt