Pyright Configuration

Understanding Pyright Configuration Core Concepts

– What is pyrightconfig.json?:
pyrightconfig.json is the configuration file placed at the root of a workspace to configure Pyright (and Pylance in VS Code).
It controls how Python source files are discovered, which virtual environments are used to resolve third-party types, and how strictly typing rules are enforced.

– Key configuration properties:
include: Array of directory paths that Pyright traverses to find source code to diagnose.
exclude: Array of file/directory glob patterns that must NOT be diagnosed as project source files (crucial for virtual environments and build artifacts).
ignore: Array of file patterns where diagnostics (errors/warnings) are silenced, even if the files are parsed.
venvPath & venv: Direct pointers to the directory containing installed packages (site-packages) used solely for dependency resolution.
executionEnvironments: Per-directory configurations allowing different rules, root paths, or settings for specific sub-projects.

Standard Setup: Single-Module / Single-Repository

– Project topology:
In a standard, single-package repository, the virtual environment is typically located at the project root (e.g. .venv or venv), alongside the application source code:

my-single-project/
├── .venv/
├── src/
│   ├── __init__.py
│   └── main.py
├── tests/
└── pyrightconfig.json

– Recommended configuration for a single project:
In this setup, you define the root . as the venvPath and target only your application folders in include.

{
  "venvPath": ".",
  "venv": ".venv",
  "include": [
    "src",
    "tests"
  ],
  "exclude": [
    "**/.venv",
    "**/venv",
    "**/node_modules",
    "**/__pycache__",
    "build",
    "dist"
  ],
  "pythonVersion": "3.11",
  "typeCheckingMode": "basic",
  "useLibraryCodeForTypes": true
}

Advanced Setup: Monorepo & Multi-Module Architecture

– Monorepo challenges:
In a monorepo containing multiple Python services, shared internal libraries, or frontend code (Node.js/React), a global scan will fail or crawl to a halt.
Common complexities include:
– Virtual environments located inside specific sub-folders (e.g., contact_flask/venv).
– Shared internal packages imported without being installed in site-packages.
– Non-Python directories (like node_modules) and experimental code paths that must be skipped.

– Monorepo folder structure example:

monorepo-workspace/
├── contact_flask/          # Flask service
│   ├── venv/               # Service-specific virtual environment
│   ├── app.py
│   └── routes/
├── contact_lib/            # Shared internal Python library
│   └── model/
│       └── ref/            # Legacy or generated files to ignore
├── frontend/               # React / Node.js application
│   └── node_modules/
└── pyrightconfig.json      # Workspace root configuration

– Production-ready Monorepo configuration:
Here is how to scope Pyright to analyze the target backend module while keeping external and shared dependencies properly resolved:

{
  "venvPath": "contact_flask",
  "venv": "venv",
  "include": [
    "contact_flask"
  ],
  "exclude": [
    "contact_flask/venv",
    "**/venv",
    "**/.venv",
    "**/node_modules",
    "**/__pycache__",
    "src/experimental",
    "src/typestubs",
    "**/marshmallow"
  ],
  "ignore": [
    "contact_lib/model/ref/**/*"
  ],
  "executionEnvironments": [
    {
      "root": "contact_flask",
      "reportPrivateImportUsage": false,
      "reportInvalidTypeForm": false,
      "reportMissingImports": "none"
    }
  ]
}

Granular Control with executionEnvironments

– Why use executionEnvironments?:
The executionEnvironments block allows you to apply custom compiler rules, extra import paths, or diagnostic strictness levels to specific sub-trees in your repository.

– Key executionEnvironment parameters:
root: Defines the subdirectory where this specific environment profile applies.
extraPaths: Adds custom directories to the module resolution path (ideal for local shared libraries like contact_lib without installing them in editable mode).
reportMissingImports: Sets the warning/error level when a module cannot be resolved ("none", "warning", or "error").
reportPrivateImportUsage: Silences warnings when accessing underscore-prefixed or internal attributes from third-party libraries.

Performance Best Practices & Debugging

– The « Nested venv » trap:
Setting "venvPath": "contact_flask" and "venv": "venv" tells Pyright where to look for imported libraries.
However, if "include": ["contact_flask"] is defined without adding "contact_flask/venv" to exclude, Pyright will traverse the entire site-packages folder as if it were your own project code, causing huge execution delays.

– Validating your configuration with –stats:
Always run the Pyright CLI with the --stats flag to inspect file count and timing metrics:

# Execute Pyright with detailed performance metrics
python -m pyright --stats

– What to look for in the output:
Files analyzed: Should match only your actual source files (e.g. 50 to 500 files), not thousands.
Time spent: A well-configured Pyright scan should complete in under 3 seconds.

Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *