How to type-check self-contained Python scripts
A script can run successfully with uv while Pyrefly reports missing imports because it checks a different environment. Configure Pyrefly to find the virtual environmentAn isolated folder where Python installs packages for one project, keeping them separate from other projects and your system Python. Learn more → that uv manages for each script.
ty also supports checking standalone scripts. This procedure uses Pyrefly with uv’s environment discovery.
Prerequisites
- uv installed and updated to the current release.
- An existing self-contained script with PEP 723 inline metadata declaring its dependencies. The commands use
example.py; substitute your script’s filename.
The commands work in macOS/Linux shells and Windows PowerShell. Run them from the directory containing the script.
Sync the script’s dependencies
Create or update the script’s environment without running the script:
uv sync --script example.pyuv reports dependency resolution and any packages it installs into the script’s cached environment. If the environment is already current, it reports that the packages were checked.
Configure Pyrefly in pyproject.toml
Open your project’s pyproject.toml, which may be in the script’s folder or a parent folder. Add this section. If [tool.pyrefly] already exists, add only the script-command setting inside that section, before the next table header:
[tool.pyrefly]
# Ask uv where each script's Python environment is installed.
script-command = [
"uv", "workspace", "metadata",
"--preview-features", "workspace-metadata",
"--script",
]Pyrefly uses this command to find the interpreter and dependencies that uv installed for each script. The preview flag enables uv’s environment-discovery feature. Discovery does not install dependencies, so the sync step must come first.
If your project already uses pyrefly.toml, add the same script-command setting at the top level, before any table headers. Omit [tool.pyrefly] and reuse the existing file, including one in a parent folder, to preserve the other project settings.
For a script outside a project with no existing Pyrefly configuration, create pyproject.toml next to it with this [tool.pyrefly] section.
Check the script
Run Pyrefly through uvx, which runs tools in a separate environment:
uvx pyrefly@latest check example.pyPyrefly checks imports against the script’s environment and reports 0 errors when the check passes. Type errors still produce diagnostics and a nonzero exit code. @latest selects the current Pyrefly release even if uv has cached an older one.
If Pyrefly warns that no script environment was found, it falls back to ordinary environment discovery, which may report missing imports. Run the sync step again after changing the script’s dependencies or before checking it on another machine.