VSCode Python Setup++

This is based on this great boilerplate for setting up Python.

I’ve adapted for my use:

  • VSCode
  • Linux on Ubuntu

Environment

Use direnv and you’ll get your enviro variable set based on your cwd.

Use this .envrc in each project to source .env and load venv:

# .envrc
# https://stackoverflow.com/questions/19331497/set-environment-variables-from-file-of-key-value-pairs
export $(grep -v '^#' .env | xargs -d '\n')

# venv
source .venv/bin/activate

# bug fix: https://github.com/direnv/direnv/wiki/PS1
unset PS1

And put your variable here in .env without ‘export’ statements

AUTOLOGIN_LOG_LEVEL=INFO
AUTOLOGIN_ENDPOINT=https://servercom/autologin
PHISAVER_LOG_LEVEL=INFO

Python

Setup Venv

sudo apt install python3.10
mkdir myproject && cd myproject
# Be sure to start with the python version you want (not just 'python')
python3.10 -m venv venv
# With your .env and .envrc (above) and direnv load the venv:
direnv allow

Project Settings

Create a pyproject.toml file and put everything you can in there. This is preferred to shitloads of .ini files.

See this great boilerplate. I add:

# pyproject.toml
[tool.pytest.ini_options]
python_files = ["autologin/tests.py","tests.py","test_*.py","*_tests.py"]
DJANGO_SETTINGS_MODULE = "webapp.settings"

Code (VSCode)

Install Extensions and Modules

First, make sure you are using the right python (check in terminal with ‘where python’ and in GUI on bottom right. It should be from the venv. Then install:

  • python (Microsoft) : required
  • Black Formatter (Microsoft) : nice formatting on save
  • ruff: fast linting
  • (Remote Development Pack): if you wanna SSH to servers and run. Not covered here.

You probably need install modules :

  • pip install pytest

Setup Code

Run Code and open the folder. Two settings.json are confusing! I keep the user one empty or very simple (typically at ~/.config/Code/User/settings.json) with just a colour scheme. On the server/s set scheme differently so you don’t mess up things!

Put the ~/myproject/.vscode/settings.json in version control and settings in that:

{
    "python.testing.pytestEnabled": true,
    "python.testing.autoTestDiscoverOnSaveEnabled": false,
    "editor.codeActionsOnSave": {
            "source.organizeImports": true
        },
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "ms-python.black-formatter",
    "ruff.args": [
        "--config=./pyproject.toml"
    ],
    "python.analysis.inlayHints.pytestParameters": true,
    
}


Gooooooooal

You wanna have the following:

  • ruff (linting)
  • Black (formatting)
  • pytest with VSCode GUI (testing, duh)

It should look like this – note imports are formatted, sorted, linting underlining and testing:

image 19
VSCode, ruff, pytest, Black

Leave a Reply

Your email address will not be published. Required fields are marked *