Python

Editing Python in Zed

When editing Python, Zed provides code intelligence using the Pyright language server.

Virtual Environments

A python virtual environment allows you store all of a project's dependencies, including the Python interpreter and package manager, in a single directory that's isolated from any other Python projects on your computer.

By default, the Pyright language server will look for Python packages in the default global locations. But you can also configure Pyright to use the packages installed in a given virtual environment.

To do this, create a JSON file called pyrightconfig.json at the root of your project. This file must include two keys:

  • venvPath: a relative path from your project directory to any directory that contains one or more a virtual environment directories
  • venv: the name of a virtual environment directory

For example, a common approach is to create a virtual environment folder called .venv at the root of your project directory with the following commands:

# create a virtual environment in the .venv folder
python3 -m venv .venv
# set up the current shell to use that virtual environment
. .venv/bin/activate   

Having done that, you would create a pyrightconfig.json with the following content:

{
  "venvPath": ".",
  "venv": ".venv"
}

For more information, see the Pyright configuration documentation.

Code Formatting

The Pyright language server does not provide code formatting. If you want to automatically reformat your Python code when saving, you'll need to specify an external code formatter in your settings. See the configuration documentation for more information.

A common tool for formatting python code is Black. If you have Black installed globally, you can use it format Python files by adding the following to your settings.json:

{
  "language_overrides": {
    "Python": {
      "format_on_save": {
        "external": {
          "command": "black",
          "arguments": [
            "-"
          ]
        }
      }
    }
  }
}