Visual Studio Code for Python Development

Table of Contents


Installation and Setup

Installing VS Code

Windows:

# Download from official website
# https://code.visualstudio.com/

# Or using winget
winget install Microsoft.VisualStudioCode

macOS:

# Using Homebrew
brew install --cask visual-studio-code

Linux (Ubuntu/Debian):

# Download .deb package or use snap
sudo snap install code --classic

# Or using apt
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg
sudo install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/
sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/code stable main" > /etc/apt/sources.list.d/vscode.list'
sudo apt update
sudo apt install code

First Launch Setup

  1. Open VS Code
  2. Install Python Extension (will be covered in next section)
  3. Configure Settings
  4. File → Preferences → Settings (or Ctrl+,)
  5. Choose Theme
  6. File → Preferences → Color Theme (Ctrl+K Ctrl+T)

Essential Extensions

Must-Have Python Extensions

1. Python (by Microsoft)

Installation: - Open Extensions view: Ctrl+Shift+X - Search "Python" - Click Install on "Python" by Microsoft

Features: - IntelliSense (code completion) - Linting (code analysis) - Debugging - Code formatting - Jupyter Notebook support - Testing support

Extension ID: ms-python.python

2. Pylance (by Microsoft)

Features: - Fast, feature-rich language support - Type checking - Auto-imports - Better IntelliSense

Extension ID: ms-python.vscode-pylance

Note: Usually installed automatically with Python extension

3. Python Indent

Features: - Correct Python indentation

Extension ID: KevinRose.vsc-python-indent

Code Quality

1. Pylint

# Install pylint
pip install pylint
  • Real-time linting
  • Code quality checks

2. Black Formatter

# Install black
pip install black
  • Automatic code formatting
  • Extension ID: ms-python.black-formatter

3. isort

# Install isort
pip install isort
  • Organize imports automatically
  • Extension ID: ms-python.isort

Additional Tools

1. autoDocstring - Generate Python docstrings automatically - Extension ID: njpwerner.autodocstring

2. Python Test Explorer - Visual test runner - Extension ID: LittleFoxTeam.vscode-python-test-adapter

3. Jupyter - Jupyter notebook support - Extension ID: ms-toolsai.jupyter

General Development

1. GitLens - Enhanced Git integration - Extension ID: eamodio.gitlens

2. Error Lens - Highlight errors inline - Extension ID: usernamehw.errorlens

3. Better Comments - Colorful comments - Extension ID: aaron-bond.better-comments

4. Path Intellisense - Autocomplete file paths - Extension ID: christian-kohler.path-intellisense

5. Material Icon Theme - Better file icons - Extension ID: PKief.material-icon-theme

Installing Multiple Extensions via Command Line

# Install all at once
code --install-extension ms-python.python
code --install-extension ms-python.vscode-pylance
code --install-extension ms-python.black-formatter
code --install-extension ms-python.isort
code --install-extension KevinRose.vsc-python-indent
code --install-extension njpwerner.autodocstring
code --install-extension eamodio.gitlens
code --install-extension usernamehw.errorlens

Python Environment Configuration

Selecting Python Interpreter

Method 1: Command Palette 1. Press Ctrl+Shift+P 2. Type "Python: Select Interpreter" 3. Choose your Python installation or virtual environment

Method 2: Status Bar - Click Python version in bottom-left status bar - Select interpreter from list

Creating Virtual Environment

From VS Code Terminal:

# Create virtual environment
python -m venv venv

# Activate it
# Windows:
venv\Scripts\activate

# Linux/Mac:
source venv/bin/activate

VS Code will automatically detect and offer to use the new virtual environment

Workspace Settings

Create .vscode/settings.json in your project:

{
    // Python interpreter
    "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python",

    // Linting
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.lintOnSave": true,

    // Formatting
    "python.formatting.provider": "black",
    "editor.formatOnSave": true,

    // Import sorting
    "isort.args": ["--profile", "black"],
    "[python]": {
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        }
    },

    // Testing
    "python.testing.pytestEnabled": true,
    "python.testing.unittestEnabled": false,

    // Editor
    "editor.rulers": [79, 120],
    "editor.tabSize": 4,
    "files.trimTrailingWhitespace": true,
    "files.insertFinalNewline": true
}

User Settings (Global)

Access: File → Preferences → Settings → User

{
    // Python
    "python.languageServer": "Pylance",
    "python.analysis.typeCheckingMode": "basic",

    // Editor
    "editor.fontSize": 14,
    "editor.lineHeight": 22,
    "editor.fontFamily": "'Fira Code', Consolas, monospace",
    "editor.fontLigatures": true,
    "editor.minimap.enabled": true,
    "editor.renderWhitespace": "boundary",

    // Files
    "files.autoSave": "afterDelay",
    "files.autoSaveDelay": 1000,
    "files.exclude": {
        "**/__pycache__": true,
        "**/*.pyc": true,
        "**/.pytest_cache": true
    },

    // Terminal
    "terminal.integrated.fontSize": 13,
    "terminal.integrated.fontFamily": "monospace"
}

Editor Features

IntelliSense and Code Completion

Trigger IntelliSense: - Automatic while typing - Manual: Ctrl+Space

Features: - Method/function suggestions - Parameter hints - Quick documentation - Auto-imports

Example:

import pandas as pd

df = pd.read_csv('data.csv')
df.  # IntelliSense shows all DataFrame methods

Linting (Code Analysis)

Enable Linting:

{
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.flake8Enabled": false,
    "python.linting.lintOnSave": true
}

Available Linters: - Pylint (comprehensive) - Flake8 (style and errors) - mypy (type checking) - pycodestyle (PEP 8)

Install Multiple Linters:

pip install pylint flake8 mypy

Code Formatting

Black (Recommended):

pip install black

Configuration:

{
    "python.formatting.provider": "black",
    "editor.formatOnSave": true,
    "[python]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "ms-python.black-formatter"
    }
}

Format Document: - Shortcut: Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac) - Right-click → Format Document

Format Selection: - Select code - Ctrl+K Ctrl+F

black configuration (pyproject.toml):

[tool.black]
line-length = 88
target-version = ['py38']
include = '\.pyi?$'

Import Organization

isort Configuration:

{
    "isort.args": ["--profile", "black"],
    "[python]": {
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        }
    }
}

Manual Sort: - Right-click → Sort Imports - Or use Command Palette: "Python: Sort Imports"

Code Navigation

Go to Definition: - F12 or Ctrl+Click - Right-click → Go to Definition

Peek Definition: - Alt+F12 - Shows definition in popup

Go to References: - Shift+F12

Go to Symbol: - Ctrl+Shift+O - Symbols in current file - Ctrl+T - Symbols in workspace

Breadcrumbs: - Shows file path and symbols - Enable: View → Show Breadcrumbs

Refactoring

Rename Symbol: - F2 on variable/function name - Renames all occurrences

Extract Variable: 1. Select expression 2. Right-click → Refactor → Extract Variable 3. Or: Ctrl+Shift+R

Extract Method: 1. Select code block 2. Right-click → Refactor → Extract Method

Quick Fix: - Ctrl+. on error/warning - Shows available fixes

Code Snippets

Built-in Python Snippets: - Type for → Tab → for loop template - Type if → Tab → if statement template - Type def → Tab → function template - Type class → Tab → class template

Custom Snippets: 1. File → Preferences → User Snippets 2. Select Python 3. Add custom snippet:

{
    "Print Debug": {
        "prefix": "pdb",
        "body": [
            "print(f'${1:variable} = {${1:variable}}')"
        ],
        "description": "Print debug statement"
    },
    "Main Guard": {
        "prefix": "main",
        "body": [
            "if __name__ == '__main__':",
            "    ${1:main()}"
        ],
        "description": "Main guard"
    }
}

Docstrings

With autoDocstring Extension: 1. Type """ below function definition 2. Press Enter 3. Auto-generates docstring template

Example:

def calculate_area(length, width):
    """_summary_

    Args:
        length (_type_): _description_
        width (_type_): _description_

    Returns:
        _type_: _description_
    """
    return length * width

Configure Style:

{
    "autoDocstring.docstringFormat": "google",
    // Options: google, numpy, sphinx, pep257
}

Debugging

Basic Debugging

Start Debugging: 1. Set breakpoint: Click left of line number (red dot) 2. Press F5 or Run → Start Debugging 3. Select "Python File"

Debug Controls: - Continue: F5 - Step Over: F10 - Step Into: F11 - Step Out: Shift+F11 - Restart: Ctrl+Shift+F5 - Stop: Shift+F5

Debug Configuration

Create launch.json: 1. Run → Add Configuration 2. Select Python 3. Choose configuration type

Example configurations:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Module",
            "type": "python",
            "request": "launch",
            "module": "mypackage.main",
            "console": "integratedTerminal"
        },
        {
            "name": "Python: Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [
                "runserver"
            ],
            "django": true
        },
        {
            "name": "Python: Flask",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "app.py",
                "FLASK_ENV": "development"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ]
        },
        {
            "name": "Python: FastAPI",
            "type": "python",
            "request": "launch",
            "module": "uvicorn",
            "args": [
                "main:app",
                "--reload"
            ]
        }
    ]
}

Debug Features

Variables View: - Shows all variables in current scope - Hover over variables to see values

Watch Expressions: - Add expressions to monitor - Debug → Add to Watch

Call Stack: - Shows function call hierarchy - Click to navigate

Debug Console: - Execute Python expressions during debugging - Access variables directly

Conditional Breakpoints: 1. Right-click breakpoint 2. Edit Breakpoint → Add condition 3. Example: i == 10 or len(data) > 100

Logpoints: 1. Right-click line number 2. Add Logpoint 3. Message will be logged without stopping execution

Remote Debugging

Install debugpy:

pip install debugpy

In your code:

import debugpy

# Wait for debugger to attach
debugpy.listen(5678)
print("Waiting for debugger...")
debugpy.wait_for_client()
print("Debugger attached!")

# Your code here

VS Code launch.json:

{
    "name": "Python: Remote Attach",
    "type": "python",
    "request": "attach",
    "connect": {
        "host": "localhost",
        "port": 5678
    }
}

Testing

pytest Configuration

Install pytest:

pip install pytest pytest-cov

Configure VS Code:

{
    "python.testing.pytestEnabled": true,
    "python.testing.unittestEnabled": false,
    "python.testing.pytestArgs": [
        "tests"
    ],
    "python.testing.autoTestDiscoverOnSaveEnabled": true
}

Running Tests

Test Explorer: - View → Testing (or click flask icon in sidebar) - Shows all discovered tests - Click play button to run tests

Keyboard Shortcuts: - Run all tests: No default (set custom) - Run test at cursor: No default (set custom) - Debug test at cursor: No default (set custom)

Command Palette: - Ctrl+Shift+P → "Python: Run All Tests" - Ctrl+Shift+P → "Python: Debug Test Method"

Test Structure

Example test file (tests/test_calculator.py):

import pytest
from calculator import add, subtract

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

def test_subtract():
    assert subtract(5, 3) == 2
    assert subtract(0, 5) == -5

def test_add_floats():
    assert add(1.5, 2.5) == 4.0

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (5, 5, 10),
    (-1, -1, -2)
])
def test_add_parametrized(a, b, expected):
    assert add(a, b) == expected

Coverage

Install coverage:

pip install pytest-cov

Run with coverage:

pytest --cov=mypackage tests/

VS Code Configuration:

{
    "python.testing.pytestArgs": [
        "tests",
        "--cov=mypackage",
        "--cov-report=html"
    ]
}

Git Integration

Basic Git Operations

Initialize Repository: - Source Control view (Ctrl+Shift+G) - Click "Initialize Repository"

Stage Changes: - Click + next to file in Source Control view - Or: Stage All Changes button

Commit: - Type commit message - Click ✓ (checkmark) or Ctrl+Enter

Push/Pull: - Click ... menu → Push/Pull

GitLens Extension

Features: - Inline blame annotations - File history - Line history - Compare branches

View Git Blame: - Hover over line to see last commit - Shows author, date, commit message

File History: - Right-click file → Open File History


Keyboard Shortcuts

Essential Shortcuts

Action Windows/Linux Mac
Command Palette Ctrl+Shift+P Cmd+Shift+P
Quick Open File Ctrl+P Cmd+P
Toggle Terminal Ctrl+` Cmd+`
Toggle Sidebar Ctrl+B Cmd+B
Save File Ctrl+S Cmd+S
Save All Ctrl+K S Cmd+K S

Editor Shortcuts

Action Windows/Linux Mac
Go to Line Ctrl+G Cmd+G
Find Ctrl+F Cmd+F
Replace Ctrl+H Cmd+H
Find in Files Ctrl+Shift+F Cmd+Shift+F
Multi-cursor Alt+Click Option+Click
Select Next Occurrence Ctrl+D Cmd+D
Column Selection Shift+Alt+Drag Shift+Option+Drag

Code Editing

Action Windows/Linux Mac
Format Document Shift+Alt+F Shift+Option+F
Go to Definition F12 F12
Peek Definition Alt+F12 Option+F12
Rename Symbol F2 F2
Quick Fix Ctrl+. Cmd+.
Toggle Comment Ctrl+/ Cmd+/
Move Line Up/Down Alt+↑/↓ Option+↑/↓
Copy Line Up/Down Shift+Alt+↑/↓ Shift+Option+↑/↓

Debugging

Action Windows/Linux Mac
Start/Continue F5 F5
Step Over F10 F10
Step Into F11 F11
Step Out Shift+F11 Shift+F11
Toggle Breakpoint F9 F9
Stop Debugging Shift+F5 Shift+F5

Terminal

Action Windows/Linux Mac
New Terminal Ctrl+Shift+` Cmd+Shift+`
Kill Terminal Delete in terminal list Delete in terminal list
Clear Terminal Ctrl+K (in terminal) Cmd+K (in terminal)

Custom Keybindings

Open Keyboard Shortcuts: - File → Preferences → Keyboard Shortcuts (Ctrl+K Ctrl+S)

Example custom keybindings (keybindings.json):

[
    {
        "key": "ctrl+shift+t",
        "command": "python.testing.runAllTests"
    },
    {
        "key": "ctrl+shift+d",
        "command": "python.testing.debugTestAtCursor"
    },
    {
        "key": "ctrl+shift+r",
        "command": "python.execInTerminal"
    }
]

Tips and Tricks

Productivity Tips

1. Multi-Cursor Editing

# Add cursor below: Ctrl+Alt+Down
# Add cursor above: Ctrl+Alt+Up
# Select all occurrences: Ctrl+Shift+L

2. Quick File Navigation - Ctrl+P → Type filename → Enter - Ctrl+P → Type @ → See symbols in file - Ctrl+P → Type : → Go to line number

3. Zen Mode - View → Appearance → Zen Mode (Ctrl+K Z) - Distraction-free coding

4. Split Editor - Ctrl+\ to split editor - Work on multiple files side-by-side

5. Code Folding - Ctrl+Shift+[ to fold - Ctrl+Shift+] to unfold - Fold all: Ctrl+K Ctrl+0 - Unfold all: Ctrl+K Ctrl+J

Python-Specific Tips

1. Run Python File - Right-click → Run Python File in Terminal - Or click ▶️ in top-right corner

2. Run Selection - Select code - Right-click → Run Selection/Line in Python Terminal - Shortcut: Shift+Enter

3. Interactive Python (REPL) - Command Palette → "Python: Start REPL"

4. Jupyter in VS Code - Create .ipynb file - Run cells interactively - Export to Python or PDF

5. Python Environments - Quick switch: Click Python version in status bar - Shows: venv, conda, system Python

Code Snippets

Useful Built-in Snippets: - for → for loop - while → while loop - if/elif → if statement - def → function - class → class definition - try → try-except - with → with statement - lambda → lambda function

Settings Sync

Enable Settings Sync: 1. Click gear icon (bottom-left) 2. Turn on Settings Sync 3. Sign in with Microsoft/GitHub account 4. Sync across multiple devices

What gets synced: - Settings - Extensions - Keyboard shortcuts - Snippets


Troubleshooting

Common Issues

Python Extension Not Working

Solution:

# Reload window
Ctrl+Shift+P → "Developer: Reload Window"

# Or reinstall extension
Ctrl+Shift+X → Uninstall Python extension → Reinstall

IntelliSense Not Working

Check: 1. Python interpreter selected? 2. Pylance installed and enabled? 3. Try: Ctrl+Shift+P → "Python: Restart Language Server"

Settings to check:

{
    "python.languageServer": "Pylance",
    "python.analysis.typeCheckingMode": "basic"
}

Linter Not Running

Solution:

# Install linter
pip install pylint

# Enable in settings
{
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true
}

# Restart VS Code

Import Errors

Check: 1. Correct Python interpreter selected? 2. Package installed in active environment? 3. Workspace folder configured correctly?

Fix:

# Verify installation
pip list | grep package-name

# Reinstall
pip install --force-reinstall package-name

Debugger Not Starting

Check: 1. Correct Python interpreter? 2. No syntax errors in file? 3. Check launch.json configuration

Try:

{
    "console": "integratedTerminal",
    "justMyCode": false
}

Terminal Not Activating Virtual Environment

Windows PowerShell:

# Enable script execution
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Linux/Mac:

# Check activation script
ls venv/bin/activate

# Manual activation
source venv/bin/activate

Performance Issues

Large Projects:

{
    // Exclude directories
    "files.exclude": {
        "**/__pycache__": true,
        "**/.pytest_cache": true,
        "**/*.pyc": true
    },

    // Limit file watching
    "files.watcherExclude": {
        "**/.git/objects/**": true,
        "**/node_modules/**": true,
        "**/venv/**": true
    },

    // Disable minimap
    "editor.minimap.enabled": false
}

Slow IntelliSense:

{
    // Reduce analysis
    "python.analysis.typeCheckingMode": "off",

    // Or use basic mode
    "python.analysis.typeCheckingMode": "basic"
}

Quick Reference

Essential Commands

Command Action
Ctrl+Shift+P Command Palette
Ctrl+P Quick Open
Ctrl+` Toggle Terminal
F5 Start Debugging
Shift+Alt+F Format Document
F12 Go to Definition
Ctrl+Shift+O Go to Symbol

Must-Have Extensions

code --install-extension ms-python.python
code --install-extension ms-python.vscode-pylance
code --install-extension ms-python.black-formatter
code --install-extension KevinRose.vsc-python-indent

Basic Settings

{
    "python.defaultInterpreterPath": "${workspaceFolder}/venv/bin/python",
    "python.formatting.provider": "black",
    "editor.formatOnSave": true,
    "python.linting.enabled": true,
    "python.testing.pytestEnabled": true
}

Additional Resources

Happy coding with VS Code! 🚀