### Install ty via PowerShell Source: https://docs.astral.sh/ty/installation Use PowerShell to download and execute the installation script on Windows. ```powershell PS> powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/ty/install.ps1 | iex" ``` ```powershell PS> powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/ty/0.0.30/install.ps1 | iex" ``` -------------------------------- ### Inspect installation scripts Source: https://docs.astral.sh/ty/installation View the contents of the installation script before execution. ```bash $ curl -LsSf https://astral.sh/ty/install.sh | less ``` ```powershell PS> powershell -c "irm https://astral.sh/ty/install.ps1 | more" ``` -------------------------------- ### Install ty globally with uv Source: https://docs.astral.sh/ty/installation Commands for installing and upgrading ty as a global tool using uv. ```bash uv tool install ty@latest ``` ```bash uv tool upgrade ty ``` -------------------------------- ### Install ty with mise Source: https://docs.astral.sh/ty/installation Commands for installing and setting ty globally using mise. ```bash mise install ty ``` ```bash mise use --global ty ``` -------------------------------- ### Install ty via standalone script Source: https://docs.astral.sh/ty/installation Use curl or wget to download and execute the installation script on macOS and Linux. ```bash $ curl -LsSf https://astral.sh/ty/install.sh | sh ``` ```bash $ wget -qO- https://astral.sh/ty/install.sh | sh ``` ```bash $ curl -LsSf https://astral.sh/ty/0.0.30/install.sh | sh ``` -------------------------------- ### Install ty with pip Source: https://docs.astral.sh/ty/installation Install ty into the current Python environment. ```bash pip install ty ``` -------------------------------- ### Run ty without installation Source: https://docs.astral.sh/ty/installation Use uvx to execute ty immediately without a permanent installation. ```bash uvx ty ``` -------------------------------- ### Start language server via CLI Source: https://docs.astral.sh/ty/editors Use the server subcommand to initiate the language server process. ```bash ty server ``` -------------------------------- ### Install ty with pipx Source: https://docs.astral.sh/ty/installation Commands for installing and upgrading ty globally using pipx. ```bash pipx install ty ``` ```bash pipx upgrade ty ``` -------------------------------- ### Install ty in Docker Source: https://docs.astral.sh/ty/installation Copy the ty binary from the official image into your Docker container. ```dockerfile COPY --from=ghcr.io/astral-sh/ty:latest /ty /bin/ ``` -------------------------------- ### Ty Server Source: https://docs.astral.sh/ty/reference/cli Starts the Ty language server. This command is used to enable language server features for Ty. ```APIDOC ## ty server ### Description Start the language server ### Usage ``` ty server ``` ### Options `--help`, `-h` Print help ``` -------------------------------- ### Configure ty Rules in Neovim Source: https://docs.astral.sh/ty/reference/editor-settings Configure ty's rules for Neovim. This example shows configurations for versions 0.11 and older. ```lua -- Neovim >=0.11: vim.lsp.config('ty', { settings = { ty = { configuration = { rules = { ["unresolved-reference"] = "warn" } } }, }, }) -- Neovim <0.11: require('lspconfig').ty.setup({ settings = { ty = { configuration = { rules = { ["unresolved-reference"] = "warn" } } }, }, }) ``` -------------------------------- ### Calculating size with list of entries Source: https://docs.astral.sh/ty/reference/typing-faq Example of a function accepting a list of entries for size calculation. ```python def total_size_bytes(entries: list[Entry]) -> int: return sum(entry.size_bytes() for entry in entries) ``` -------------------------------- ### Configure Emacs Eglot Source: https://docs.astral.sh/ty/editors Register the ty server with Eglot and ensure it starts for Python modes. ```elisp (with-eval-after-load 'eglot (add-to-list 'eglot-server-programs '(python-base-mode . ("ty" "server")))) (add-hook 'python-base-mode-hook 'eglot-ensure) ``` -------------------------------- ### Valid Constrained and Bound Type Variables Source: https://docs.astral.sh/ty/reference/rules Provides examples of correctly defined constrained and bound type variables. ```python T = TypeVar('T', str, int) # valid constrained TypeVar # or T = TypeVar('T', bound=str) # valid bound TypeVar U = TypeVar('U', list[int], int) # valid constrained Type ``` -------------------------------- ### Type Check PEP 723 Inline-Metadata Scripts with ty Source: https://docs.astral.sh/ty/reference/typing-faq Use uv's --with-requirements flag to install script dependencies before type checking with ty. This is for single inline-metadata scripts. ```bash uvx --with-requirements script.py ty check script.py ``` -------------------------------- ### Set ty Diagnostic Mode in Neovim Source: https://docs.astral.sh/ty/reference/editor-settings Set the diagnostic mode for ty in Neovim. This example shows configurations for versions >=0.11 and <0.11. ```lua -- Neovim >=0.11: vim.lsp.config('ty', { settings = { ty = { diagnosticMode = 'workspace', }, }, }) -- Neovim <0.11: require('lspconfig').ty.setup({ settings = { ty = { diagnosticMode = 'workspace', }, }, }) ``` -------------------------------- ### Resolved Global Variable Declaration Source: https://docs.astral.sh/ty/reference/rules This example shows the correct way to declare and use global variables, ensuring they have explicit definitions or declarations in the global scope to aid static analysis. ```python x: int def f(): global x x = 42 def g(): print(x) ``` -------------------------------- ### Detecting invalid match patterns Source: https://docs.astral.sh/ty/reference/rules Shows an example of a runtime TypeError caused by attempting to match against a non-class object. ```python NotAClass = 42 match x: case NotAClass(): # TypeError at runtime: must be a class ... ``` -------------------------------- ### Remove default exclusion Source: https://docs.astral.sh/ty/exclusions To include a directory that is excluded by default, add a negative exclude pattern with a leading `!`. This example removes `build` from the excluded directories. ```toml [tool.ty.src] # Remove `build` from the excluded directories. exclude = ["!**/build/"] ``` ```toml [src] # Remove `build` from the excluded directories. exclude = ["!**/build/"] ``` -------------------------------- ### Invalid Overload Definition (Missing Implementation) Source: https://docs.astral.sh/ty/reference/rules If multiple @overload decorators are used, a final implementation must be provided. This example shows an invalid case where no implementation follows. ```python from typing import overload @overload def foo() -> None: ... @overload def foo(x: int) -> int: ... ``` -------------------------------- ### Resolved Global Variable with Optional Type Source: https://docs.astral.sh/ty/reference/rules This example demonstrates using an optional type for a global variable, providing a default `None` value. This approach also aids static analysis by ensuring a defined state. ```python x: int | None = None def f(): global x x = 42 def g(): print(x) ``` -------------------------------- ### Configure Neovim (<0.11) Source: https://docs.astral.sh/ty/editors Use the lspconfig plugin to set up the language server for older Neovim versions. ```lua require('lspconfig').ty.setup({ settings = { ty = { -- ty language server settings go here } } }) ``` -------------------------------- ### Configure Neovim (>=0.11) Source: https://docs.astral.sh/ty/editors Enable the language server using the built-in lsp configuration for newer Neovim versions. ```lua -- Optional: Only required if you need to update the language server settings vim.lsp.config('ty', { settings = { ty = { -- ty language server settings go here } } }) -- Required: Enable the language server vim.lsp.enable('ty') ``` -------------------------------- ### Configure all rules via command line Source: https://docs.astral.sh/ty/rules Apply a single level to all rules using the all keyword. ```bash ty check --error all ``` -------------------------------- ### Configure Project Root Directories Source: https://docs.astral.sh/ty/reference/configuration Define the root paths for finding first-party modules. Paths are searched in priority order. ty auto-detects common layouts if not specified. ```toml [tool.ty.environment] # Multiple directories (priority order) root = ["./src", "./lib", "./vendor"] ``` ```toml [environment] # Multiple directories (priority order) root = ["./src", "./lib", "./vendor"] ``` -------------------------------- ### Configure all rules in configuration files Source: https://docs.astral.sh/ty/rules Set all rules to a specific level within the configuration file. ```toml [tool.ty.rules] all = "error" ``` ```toml [rules] all = "error" ``` -------------------------------- ### Configure Zed language servers Source: https://docs.astral.sh/ty/editors Enable ty and ruff by modifying the languages section in settings.json. ```json { "languages": { "Python": { "language_servers": [ // Enable ty and ruff, // Other built-in servers (basedpyright, pyright, pylsp) // are disabled by being omitted from this list. "ty", "ruff" ] } } } ``` -------------------------------- ### Manage ty as a project dependency Source: https://docs.astral.sh/ty/installation Commands for adding, running, and updating ty within a project using uv. ```bash uv add --dev ty ``` ```bash uv run ty ``` ```bash uv lock --upgrade-package ty ``` -------------------------------- ### Invalid NamedTuple Field Name Source: https://docs.astral.sh/ty/reference/rules NamedTuple field names cannot start with an underscore. This check prevents potential issues and ensures valid naming conventions. ```python from typing import NamedTuple >>> class Foo(NamedTuple): ... _bar: int ``` -------------------------------- ### Basic ty CLI Usage Source: https://docs.astral.sh/ty/reference/cli General syntax for invoking the ty command-line tool. ```bash ty ``` -------------------------------- ### Ty Help Source: https://docs.astral.sh/ty/reference/cli Displays general help information for the Ty CLI or specific commands. ```APIDOC ## ty help ### Description Print this message or the help of the given subcommand(s) ### Usage ``` ty help [COMMAND] ``` ``` -------------------------------- ### Enable Error on Warning Source: https://docs.astral.sh/ty/reference/configuration Configure Ty to exit with a non-zero status code (1) if any warning-level diagnostics are found. Defaults to false. ```toml [tool.ty.terminal] # Error if ty emits any warning-level diagnostics. error-on-warning = true ``` ```toml [terminal] # Error if ty emits any warning-level diagnostics. error-on-warning = true ``` -------------------------------- ### Configure rule levels via command line Source: https://docs.astral.sh/ty/rules Use flags to set specific rules to error, warn, or ignore states during execution. ```bash ty check \ --warn unused-ignore-comment \ # Make `unused-ignore-comment` a warning --ignore redundant-cast \ # Disable `redundant-cast` --error possibly-missing-attribute \ # Error on `possibly-missing-attribute` --error possibly-missing-import # Error on `possibly-missing-import` ``` -------------------------------- ### Configure include patterns Source: https://docs.astral.sh/ty/reference/configuration Specifies a list of files and directories to be included for type checking. ```toml [tool.ty.src] include = [ "src", "tests", ] ``` ```toml [src] include = [ "src", "tests", ] ``` -------------------------------- ### Configure Custom Typeshed Path Source: https://docs.astral.sh/ty/reference/configuration Provide an optional path to a local 'typeshed' directory for standard-library types. Falls back to vendored stubs if not provided. ```toml [tool.ty.environment] typeshed = "/path/to/custom/typeshed" ``` ```toml [environment] typeshed = "/path/to/custom/typeshed" ``` -------------------------------- ### Configure Project Root in ty.toml Source: https://docs.astral.sh/ty/modules Set the 'environment.root' in ty.toml to specify custom locations for first-party modules when your project layout differs from the default. ```toml [environment] root = ["./app"] ``` -------------------------------- ### Configure ty Log File (Neovim) Source: https://docs.astral.sh/ty/reference/editor-settings Specify the path to a file where the language server should write its log messages in Neovim. This requires editor restart for versions <0.11. ```lua -- Neovim >=0.11: vim.lsp.config('ty', { init_options = { logFile = '/path/to/ty.log', }, }) -- Neovim <0.11: require('lspconfig').ty.setup({ init_options = { logFile = '/path/to/ty.log', }, }) ``` -------------------------------- ### Set Project Root Directory Source: https://docs.astral.sh/ty/reference/configuration Specify the root directory for finding first-party modules. If omitted, Ty attempts to auto-detect common project layouts. ```toml [tool.ty.src] root = "./app" ``` ```toml [src] root = "./app" ``` -------------------------------- ### Configure Zed binary path Source: https://docs.astral.sh/ty/editors Specify a custom path for the ty executable in Zed settings. ```json { "lsp": { "ty": { "binary": { "path": "/home/user/.local/bin/ty", "arguments": ["server"] } } } } ``` -------------------------------- ### Configure ty rules in ty.toml Source: https://docs.astral.sh/ty/configuration Use a ty.toml file for configuration without the [tool.ty] prefix. This file takes precedence over pyproject.toml. ```toml [rules] index-out-of-bounds = "ignore" ``` -------------------------------- ### Configure include and exclude paths Source: https://docs.astral.sh/ty/exclusions Specify directories to include and exclude for ty's analysis. This configuration is typically placed in `pyproject.toml` or `ty.toml`. ```toml [tool.ty.src] include = ["src", "tests"] exclude = ["src/generated"] ``` ```toml [src] include = ["src", "tests"] exclude = ["src/generated"] ``` -------------------------------- ### Project Root Configuration Source: https://docs.astral.sh/ty/reference/configuration Specify the root paths of the project for finding first-party modules. ```APIDOC ## `root` ### Description The root paths of the project, used for finding first-party modules. Accepts a list of directory paths searched in priority order (first has highest priority). If left unspecified, ty will try to detect common project layouts and initialize `root` accordingly. The project root (`.`) is always included. Additionally, the following directories are included if they exist and are not packages (i.e. they do not contain `__init__.py` or `__init__.pyi` files): * `./src` * `./` (if a `.//` directory exists) * `./python` ### Default value `null` ### Type `list[str]` ### Example usage ```toml [tool.ty.environment] # Multiple directories (priority order) root = ["./src", "./lib", "./vendor"] ``` ```toml [environment] # Multiple directories (priority order) root = ["./src", "./lib", "./vendor"] ``` ``` -------------------------------- ### Configure imports replaced with Any Source: https://docs.astral.sh/ty/reference/configuration Replaces type information for specified modules with typing.Any. ```toml [tool.ty.analysis] # Replace all pandas and numpy imports with Any replace-imports-with-any = ["pandas.**", "numpy.**"] ``` ```toml [analysis] # Replace all pandas and numpy imports with Any replace-imports-with-any = ["pandas.**", "numpy.**"] ``` -------------------------------- ### Configure Python Platform for Analysis Source: https://docs.astral.sh/ty/reference/configuration Specify the target platform for code analysis to understand platform-specific conditions. If 'all' is specified, ty assumes the code runs on any platform. Otherwise, it defaults to the current platform. ```toml [tool.ty.environment] # Tailor type stubs and conditionalized type definitions to windows. python-platform = "win32" ``` ```toml [environment] # Tailor type stubs and conditionalized type definitions to windows. python-platform = "win32" ``` -------------------------------- ### Specify ty Configuration File in Zed Source: https://docs.astral.sh/ty/reference/editor-settings Set the path to a ty.toml configuration file within Zed's LSP settings. ```json { "lsp": { "ty": { "settings": { "configurationFile": "./.config/ty.toml" } } } } ``` -------------------------------- ### Run ty check Source: https://docs.astral.sh/ty/reference/cli Syntax for checking a project for type errors, optionally specifying paths. ```bash ty check [OPTIONS] [PATH]... ``` -------------------------------- ### Handling Arbitrary Objects in __eq__ Source: https://docs.astral.sh/ty/reference/rules Shows the conventional way to implement `__eq__` to gracefully handle comparisons with objects of unexpected types, preventing exceptions. ```python class A: x: int def __eq__(self, other: object) -> bool: # gracefully handle an object of an unexpected type # without raising an exception if not isinstance(other, A): return False return self.x == other.x ``` -------------------------------- ### Configure ty Log File (Zed) Source: https://docs.astral.sh/ty/reference/editor-settings Specify the path to a file where the language server should write its log messages in Zed. By default, logs go to stderr. ```json { "lsp": { "ty": { "initialization_options": { "logFile": "/path/to/ty.log" } } } } ``` -------------------------------- ### Enable Auto-Import Suggestions (Zed) Source: https://docs.astral.sh/ty/reference/editor-settings Configure Zed to include auto-import suggestions in code completions. This setting is a boolean. ```json { "lsp": { "ty": { "settings": { "completions": { "autoImport": true } } } } } ``` -------------------------------- ### Ty Explain Source: https://docs.astral.sh/ty/reference/cli Provides explanations for Ty rules and other internal commands. It can explain specific rules or all rules. ```APIDOC ## ty explain ### Description Explain rules and other parts of ty ### Usage ``` ty explain ``` ### Commands `ty explain rule` Explain a rule (or all rules) `ty explain help` Print this message or the help of the given subcommand(s) ``` ```APIDOC ### ty explain rule ### Description Explain a rule (or all rules) ### Usage ``` ty explain rule [OPTIONS] [RULE] ``` ### Arguments `RULE` Rule to explain Defaults to all rules if omitted. ### Options `--help`, `-h` Print help (see a summary with '-h') `--output-format` _output-format_ Output format [default: text] Possible values: * `text` * `json` ``` ```APIDOC ### ty explain help ### Description Print this message or the help of the given subcommand(s) ### Usage ``` ty explain help [COMMAND] ``` ``` -------------------------------- ### Specify ty Configuration File in Neovim Source: https://docs.astral.sh/ty/reference/editor-settings Configure the path to a ty.toml configuration file in Neovim. Supports versions >=0.11 and <0.11. ```lua -- Neovim >=0.11: vim.lsp.config('ty', { settings = { ty = { configurationFile = "./.config/ty.toml" }, }, }) -- Neovim <0.11: require('lspconfig').ty.setup({ settings = { ty = { configurationFile = "./.config/ty.toml" }, }, }) ``` -------------------------------- ### Configure Multiple Source Roots for ty in Monorepos Source: https://docs.astral.sh/ty/reference/typing-faq Define multiple source directories for ty to recognize in a monorepo. Be aware this may lead to importability issues at runtime. ```toml [tool.ty.environment] root = ["packages/package-a", "packages/package-b"] ``` -------------------------------- ### Inlay Hints Settings Source: https://docs.astral.sh/ty/reference/editor-settings Settings that control the inline hints provided by the ty language server within an editor. ```APIDOC ## `inlayHints` ### Description These settings control the inline hints that ty provides in an editor. ``` -------------------------------- ### Typeshed Configuration Source: https://docs.astral.sh/ty/reference/configuration Provide an optional path to a 'typeshed' directory for standard-library types. ```APIDOC ## `typeshed` ### Description Optional path to a "typeshed" directory on disk for us to use for standard-library types. If this is not provided, we will fallback to our vendored typeshed stubs for the stdlib, bundled as a zip file in the binary ### Default value `null` ### Type `str` ### Example usage ```toml [tool.ty.environment] typeshed = "/path/to/custom/typeshed" ``` ```toml [environment] typeshed = "/path/to/custom/typeshed" ``` ``` -------------------------------- ### Configuration File Path Source: https://docs.astral.sh/ty/reference/editor-settings Specifies the path to a ty.toml configuration file, which will be used over any automatically discovered configuration. ```APIDOC ## `configurationFile` ### Description The path to a `ty.toml` configuration file. ty will use the specified configuration over any automatically discovered configuration. ty will expand a tilde `~` at the start of a string to the user's home directory, as well as variables like `$A` or `${A}`. Info While ty configuration can be included in a `pyproject.toml` file, it is not allowed in this context. ### Default value `null` ### Type `string` ### Example usage ```json { "ty.configurationFile": "./.config/ty.toml" } ``` ```javascript // Neovim >=0.11: vim.lsp.config('ty', { settings = { ty = { configurationFile = "./.config/ty.toml" }, }, }) // Neovim <0.11: require('lspconfig').ty.setup({ settings = { ty = { configurationFile = "./.config/ty.toml" }, }, }) ``` ```json { "lsp": { "ty": { "settings": { "configurationFile": "./.config/ty.toml" } } } } ``` ``` -------------------------------- ### Configure rule overrides for specific files Source: https://docs.astral.sh/ty/reference/configuration Apply different rule configurations to specific files or directories using glob patterns. ```toml [[tool.ty.overrides]] include = ["tests/**", "**/test_*.py"] [tool.ty.overrides.rules] possibly-unresolved-reference = "warn" ``` ```toml [[tool.ty.overrides]] include = ["generated/**"] exclude = ["generated/important.py"] [tool.ty.overrides.rules] possibly-unresolved-reference = "ignore" ``` -------------------------------- ### Include files for overrides Source: https://docs.astral.sh/ty/reference/configuration Specify which files or directories are affected by the override. ```toml [[tool.ty.overrides]] include = [ "src", "tests", ] ``` ```toml [[overrides]] include = [ "src", "tests", ] ``` -------------------------------- ### Configure ty rules in pyproject.toml Source: https://docs.astral.sh/ty/configuration Add the [tool.ty] table to your pyproject.toml to define project-specific rules. ```toml [tool.ty.rules] index-out-of-bounds = "ignore" ``` -------------------------------- ### Enable Auto-Import Suggestions (Neovim) Source: https://docs.astral.sh/ty/reference/editor-settings Configure Neovim to include auto-import suggestions in code completions. This setting is a boolean and requires editor restart for Neovim <0.11. ```lua -- Neovim >=0.11: vim.lsp.config('ty', { settings = { ty = { completions = { autoImport = true, }, }, }, }) -- Neovim <0.11: require('lspconfig').ty.setup({ settings = { ty = { completions = { autoImport = true, }, }, }, }) ``` -------------------------------- ### Configure rule levels in configuration files Source: https://docs.astral.sh/ty/rules Define rule levels within pyproject.toml or ty.toml configuration files. ```toml [tool.ty.rules] unused-ignore-comment = "warn" redundant-cast = "ignore" possibly-missing-attribute = "error" possibly-missing-import = "error" ``` ```toml [rules] unused-ignore-comment = "warn" redundant-cast = "ignore" possibly-missing-attribute = "error" possibly-missing-import = "error" ``` -------------------------------- ### Run the type checker Source: https://docs.astral.sh/ty/type-checking Executes the type checker on the current project or directory. ```bash ty check ``` -------------------------------- ### Replace module imports with Any Source: https://docs.astral.sh/ty/reference/configuration Force imports matching glob patterns to be treated as typing.Any. ```toml [tool.ty.overrides.analysis] # Replace all pandas and numpy imports with Any replace-imports-with-any = ["pandas.**", "numpy.**"] ``` ```toml [overrides.analysis] # Replace all pandas and numpy imports with Any replace-imports-with-any = ["pandas.**", "numpy.**"] ``` -------------------------------- ### Configure extra module resolution paths Source: https://docs.astral.sh/ty/reference/configuration Adds user-provided paths to the module resolution priority list. ```toml [tool.ty.environment] extra-paths = ["./shared/my-search-path"] ``` ```toml [environment] extra-paths = ["./shared/my-search-path"] ``` -------------------------------- ### Configure Project Root in pyproject.toml Source: https://docs.astral.sh/ty/modules Set the 'environment.root' in pyproject.toml to specify custom locations for first-party modules when your project layout differs from the default. ```toml [tool.ty.environment] root = ["./app"] ``` -------------------------------- ### Configure logLevel in Neovim Source: https://docs.astral.sh/ty/reference/editor-settings Set the log level using Neovim's lspconfig or built-in LSP configuration. ```lua -- Neovim >=0.11: vim.lsp.config('ty', { init_options = { logLevel = 'debug', }, }) -- Neovim <0.11: require('lspconfig').ty.setup({ init_options = { logLevel = 'debug', }, }) ``` -------------------------------- ### Set VS Code Import Strategy Source: https://docs.astral.sh/ty/reference/editor-settings Configure the VS Code extension to use the bundled 'ty' executable. This setting determines how the 'ty' executable is loaded. ```json { "ty.importStrategy": "useBundled" } ``` -------------------------------- ### Configure ty Log File (VS Code) Source: https://docs.astral.sh/ty/reference/editor-settings Specify the path to a file where the language server should write its log messages in VS Code. By default, logs go to stderr. ```json { "ty.logFile": "/path/to/ty.log" } ``` -------------------------------- ### Specify ty Executable Path Source: https://docs.astral.sh/ty/reference/editor-settings Provide a list of paths to 'ty' executables for the VS Code extension. The extension uses the first executable that exists and this setting takes precedence over 'ty.importStrategy'. ```json { "ty.path": ["/home/user/.local/bin/ty"] } ``` -------------------------------- ### Configure respect-ignore-files Source: https://docs.astral.sh/ty/reference/configuration Toggles whether to automatically exclude files ignored by version control ignore files. ```toml [tool.ty.src] respect-ignore-files = false ``` ```toml [src] respect-ignore-files = false ``` -------------------------------- ### Python 3.10 Match Statement and sys.stdlib_module_names Usage Source: https://docs.astral.sh/ty/python-version Demonstrates the use of Python 3.10's `match` statement and `sys.stdlib_module_names`. Note that `match` causes a syntax error in versions prior to 3.10, and `sys.stdlib_module_names` causes an unresolved attribute error. Usage of newer features should be guarded by version checks. ```python import sys # `invalid-syntax` error if `python-version` is set to 3.9 or lower: match "echo hello".split(): case ["echo", message]: print(message) case _: print("unknown command") # `unresolved-attribute` error if `python-version` is set to 3.9 or lower: print(sys.stdlib_module_names) if sys.version_info >= (3, 10): # ok, because the usage is guarded by a version check: print(sys.stdlib_module_names) ``` -------------------------------- ### Run ty per-package in a Monorepo Source: https://docs.astral.sh/ty/reference/typing-faq Execute ty checks on individual packages within a monorepo. Use the --project flag to specify the target package directory. ```bash ty check --project packages/package-a ty check --project packages/package-b ``` -------------------------------- ### Apply gradual typing guarantees Source: https://docs.astral.sh/ty/features/type-system Shows how ty avoids false positives in untyped code by treating attributes as Unknown | None. ```python class RetryPolicy: max_retries = None policy = RetryPolicy() policy.max_retries = 1 ``` -------------------------------- ### Specify ty Configuration File in VS Code Source: https://docs.astral.sh/ty/reference/editor-settings Set the path to a ty.toml configuration file in VS Code. This overrides any automatically discovered configurations. ```json { "ty.configurationFile": "./.config/ty.toml" } ``` -------------------------------- ### Configure logLevel in VS Code Source: https://docs.astral.sh/ty/reference/editor-settings Set the log level via the VS Code settings configuration. ```json { "ty.logLevel": "debug" } ``` -------------------------------- ### Enable Auto-Import Suggestions (VS Code) Source: https://docs.astral.sh/ty/reference/editor-settings Configure VS Code to include auto-import suggestions in code completions. This setting is a boolean. ```json { "ty.completions.autoImport": true } ``` -------------------------------- ### Configure ty Rules in VS Code Source: https://docs.astral.sh/ty/reference/editor-settings Use this to configure specific rules for the ty language server in VS Code. The inline settings take precedence over configuration files. ```json { "ty.configuration": { "rules": { "unresolved-reference": "warn" } } } ``` -------------------------------- ### Run ty Type Checker with uvx Source: https://docs.astral.sh/ty Use uvx to quickly run the ty type checker. It checks all Python files in the current directory or project by default. ```bash uvx ty check ``` -------------------------------- ### Set ty Diagnostic Mode in Zed Source: https://docs.astral.sh/ty/reference/editor-settings Configure ty's diagnostic mode in Zed. Setting to 'workspace' enables diagnostics for the entire workspace. ```json { "lsp": { "ty": { "settings": { "diagnosticMode": "workspace" } } } } ``` -------------------------------- ### Python Platform Configuration Source: https://docs.astral.sh/ty/reference/configuration Specify the target platform for source code analysis. ```APIDOC ## `python-platform` ### Description Specifies the target platform that will be used to analyze the source code. If specified, ty will understand conditions based on comparisons with `sys.platform`, such as are commonly found in typeshed to reflect the differing contents of the standard library across platforms. If `all` is specified, ty will assume that the source code can run on any platform. If no platform is specified, ty will use the current platform: - `win32` for Windows - `darwin` for macOS - `android` for Android - `ios` for iOS - `linux` for everything else ### Default value `` ### Type `"win32" | "darwin" | "android" | "ios" | "linux" | "all" | str` ### Example usage ```toml [tool.ty.environment] # Tailor type stubs and conditionalized type definitions to windows. python-platform = "win32" ``` ```toml [environment] # Tailor type stubs and conditionalized type definitions to windows. python-platform = "win32" ``` ``` -------------------------------- ### Python Environment Configuration Source: https://docs.astral.sh/ty/reference/configuration Configure the path to your project's Python environment or interpreter. ```APIDOC ## `python` ### Description Path to your project's Python environment or interpreter. ty uses the `site-packages` directory of your project's Python environment to resolve third-party (and, in some cases, first-party) imports in your code. This can be a path to: * A Python interpreter, e.g. `.venv/bin/python3` * A virtual environment directory, e.g. `.venv` * A system Python [`sys.prefix`] directory, e.g. `/usr` If you're using a project management tool such as uv, you should not generally need to specify this option, as commands such as `uv run` will set the `VIRTUAL_ENV` environment variable to point to your project's virtual environment. ty can also infer the location of your environment from an activated Conda environment, and will look for a `.venv` directory in the project root if none of the above apply. Failing that, ty will look for a `python3` or `python` binary available in `PATH`. ### Default value `null` ### Type `str` ### Example usage ```toml [tool.ty.environment] python = "./custom-venv-location/.venv" ``` ```toml [environment] python = "./custom-venv-location/.venv" ``` ``` -------------------------------- ### Valid ParamSpec Creation Source: https://docs.astral.sh/ty/reference/rules Demonstrates the correct way to create a ParamSpec. The name of the ParamSpec must match the variable it is assigned to. ```python from typing import ParamSpec P1 = ParamSpec("P1") # okay P2 = ParamSpec("S2") # error: ParamSpec name must match the variable it's assigned to ``` -------------------------------- ### Configure VS Code settings Source: https://docs.astral.sh/ty/editors Override default language server behavior by modifying the settings.json file. ```json { "python.languageServer": "Pylance", "ty.disableLanguageServices": true, } ``` -------------------------------- ### Ty Generate Shell Completion Source: https://docs.astral.sh/ty/reference/cli Generates shell completion scripts for various shells. ```APIDOC ## ty generate-shell-completion ### Description Generate shell completion ### Usage ``` ty generate-shell-completion ``` ### Arguments `SHELL` ### Options `--help`, `-h` Print help ``` -------------------------------- ### Enable shell autocompletion Source: https://docs.astral.sh/ty/installation Commands to generate and register shell completion scripts for various shells. ```bash echo 'eval "$(ty generate-shell-completion bash)"' >> ~/.bashrc ``` ```bash echo 'eval "$(ty generate-shell-completion zsh)"' >> ~/.zshrc ``` ```bash echo 'ty generate-shell-completion fish | source' > ~/.config/fish/completions/ty.fish ``` ```bash echo 'eval (ty generate-shell-completion elvish | slurp)' >> ~/.elvish/rc.elv ``` ```powershell if (!(Test-Path -Path $PROFILE)) { New-Item -ItemType File -Path $PROFILE -Force } Add-Content -Path $PROFILE -Value '(& ty generate-shell-completion powershell) | Out-String | Invoke-Expression' ``` -------------------------------- ### Configure exclude patterns Source: https://docs.astral.sh/ty/reference/configuration Defines a list of file and directory patterns to exclude from type checking using gitignore-style syntax. ```toml [tool.ty.src] exclude = [ "generated", "*.proto", "tests/fixtures/**", "!tests/fixtures/important.py" # Include this one file ] ``` ```toml [src] exclude = [ "generated", "*.proto", "tests/fixtures/**", "!tests/fixtures/important.py" # Include this one file ] ``` -------------------------------- ### Editor Settings Configuration Source: https://docs.astral.sh/ty/reference/editor-settings Configuration of ty's settings within the editor. Inline settings take precedence over configuration files. ```APIDOC ## `configuration` ### Description In-editor configuration of ty's settings. The inline settings always take precedence over the settings from configuration files, including the configuration specified with `configurationFile`. Consult the configuration reference for a list of all supported configuration options. ### Default value `null` ### Type `object` ### Example usage ```json { "ty.configuration": { "rules": { "unresolved-reference": "warn" } } } ``` ```javascript // Neovim >=0.11: vim.lsp.config('ty', { settings = { ty = { configuration = { rules = { ["unresolved-reference"] = "warn" } } }, }, }) // Neovim <0.11: require('lspconfig').ty.setup({ settings = { ty = { configuration = { rules = { ["unresolved-reference"] = "warn" } } }, }, }) ``` ```json { "lsp": { "ty": { "settings": { "configuration": { "rules": { "unresolved-reference": "warn" } } } } } } ``` ``` -------------------------------- ### Set ty Diagnostic Mode in VS Code Source: https://docs.astral.sh/ty/reference/editor-settings Configure the diagnostic mode for ty in VS Code. Setting to 'workspace' reports diagnostics for all files in the workspace. ```json { "ty.diagnosticMode": "workspace" } ``` -------------------------------- ### Exclude virtual environment files Source: https://docs.astral.sh/ty/exclusions Create a `.gitignore` file within your virtual environment directory (e.g., `.venv`) to prevent ty from analyzing its contents. This is particularly useful for older Python versions. ```bash echo "*" > .venv/.gitignore ``` -------------------------------- ### Set Terminal Output Format Source: https://docs.astral.sh/ty/reference/configuration Define the format for displaying diagnostic messages. Supported formats include 'full', 'concise', 'github', 'gitlab', and 'junit'. Defaults to 'full'. ```toml [tool.ty.terminal] output-format = "concise" ``` ```toml [terminal] output-format = "concise" ``` -------------------------------- ### Configure Python Interpreter Path Source: https://docs.astral.sh/ty/reference/configuration Specify the path to your project's Python environment or interpreter. ty uses this to resolve imports. This can be a path to an interpreter, a virtual environment directory, or a system Python prefix. ```toml [tool.ty.environment] python = "./custom-venv-location/.venv" ``` ```toml [environment] python = "./custom-venv-location/.venv" ``` -------------------------------- ### Demonstrating list invariance Source: https://docs.astral.sh/ty/reference/typing-faq Explains why list[Subtype] cannot be used where list[Supertype] is expected due to mutability. ```python # Setup of `Entry`, `Directory`, and `File` classes def modify(entries: list[Entry]): entries.append(File("README.txt")) # mutation directories: list[Directory] = [Directory("Downloads"), Directory("Documents")] modify(directories) # ty emits an error on this call ``` ```python for directory in directories: directory.children() # runtime: 'File' object has no attribute 'children' ``` -------------------------------- ### Configure logLevel in Zed Source: https://docs.astral.sh/ty/reference/editor-settings Set the log level within the Zed editor's LSP configuration block. ```json { "lsp": { "ty": { "initialization_options": { "logLevel": "debug" } } } } ``` -------------------------------- ### Exclude files from overrides Source: https://docs.astral.sh/ty/reference/configuration Define patterns to exclude from an override, supporting gitignore-style syntax. ```toml [[tool.ty.overrides]] exclude = [ "generated", "*.proto", "tests/fixtures/**", "!tests/fixtures/important.py" # Include this one file ] ``` ```toml [[overrides]] exclude = [ "generated", "*.proto", "tests/fixtures/**", "!tests/fixtures/important.py" # Include this one file ] ``` -------------------------------- ### Specify Python Interpreter Path for ty Source: https://docs.astral.sh/ty/reference/editor-settings Provide a list of paths to Python interpreters for the VS Code extension to find the 'ty' executable when 'ty.importStrategy' is 'fromEnvironment'. Only the first interpreter in the list is used. ```json { "ty.interpreter": ["/home/user/.local/bin/python"] } ``` -------------------------------- ### Python Version Configuration Source: https://docs.astral.sh/ty/reference/configuration Define the Python version for source code analysis. ```APIDOC ## `python-version` ### Description Specifies the version of Python that will be used to analyze the source code. The version should be specified as a string in the format `M.m` where `M` is the major version and `m` is the minor (e.g. `"3.7"` or `"3.12"`). If a version is provided, ty will generate errors if the source code makes use of language features that are not supported in that version. If a version is not specified, ty will try the following techniques in order of preference to determine a value: 1. Check for the `project.requires-python` setting in a `pyproject.toml` file and use the minimum version from the specified range 2. Check for an activated or configured Python environment and attempt to infer the Python version of that environment 3. Fall back to the default value (see below) For some language features, ty can also understand conditionals based on comparisons with `sys.version_info`. These are commonly found in typeshed, for example, to reflect the differing contents of the standard library across Python versions. ### Default value `"3.14"` ### Type `"3.7" | "3.8" | "3.9" | "3.10" | "3.11" | "3.12" | "3.13" | "3.14" | "3.15"` ### Example usage ```toml [tool.ty.environment] python-version = "3.12" ``` ```toml [environment] python-version = "3.12" ``` ``` -------------------------------- ### Configure Python Version for Analysis Source: https://docs.astral.sh/ty/reference/configuration Specify the Python version for analysis to catch language feature incompatibilities. ty infers the version from pyproject.toml or the environment if not specified. Defaults to '3.14'. ```toml [tool.ty.environment] python-version = "3.12" ``` ```toml [environment] python-version = "3.12" ``` -------------------------------- ### Ty Version Source: https://docs.astral.sh/ty/reference/cli Displays the current version of the Ty tool. It supports different output formats. ```APIDOC ## ty version ### Description Display ty's version ### Usage ``` ty version [OPTIONS] ``` ### Options `--help`, `-h` Print help `--output-format` _output-format_ The format in which to display the version information [default: text] Possible values: * `text` * `json` ``` -------------------------------- ### Configure respect-type-ignore-comments Source: https://docs.astral.sh/ty/reference/configuration Controls whether ty respects type: ignore comments. Set to false to require ty: ignore instead. ```toml [tool.ty.overrides.analysis] # Disable support for `type: ignore` comments respect-type-ignore-comments = false ``` ```toml [overrides.analysis] # Disable support for `type: ignore` comments respect-type-ignore-comments = false ``` -------------------------------- ### Configure rule severities Source: https://docs.astral.sh/ty/reference/configuration Sets the severity level for specific rules in the configuration file. ```toml [tool.ty.rules] possibly-unresolved-reference = "warn" division-by-zero = "ignore" ``` ```toml [rules] possibly-unresolved-reference = "warn" division-by-zero = "ignore" ``` -------------------------------- ### Representing Unknown types Source: https://docs.astral.sh/ty/reference/typing-faq Demonstrates how ty represents unresolved imports as the Unknown type. ```python from missing_module import MissingClass # error: unresolved-import reveal_type(MissingClass) # Unknown ``` -------------------------------- ### Infer types with fixpoint iteration Source: https://docs.astral.sh/ty/features/type-system Illustrates how ty resolves cyclic type dependencies by iterating until the type converges. ```python class LoopingCounter: def __init__(self): self.value = 0 def tick(self): self.value = (self.value + 1) % 5 # reveals: Unknown | Literal[0, 1, 2, 3, 4] reveal_type(LoopingCounter().value) ``` -------------------------------- ### Handling Unknown in unions Source: https://docs.astral.sh/ty/reference/typing-faq Shows how ty uses Unknown in unions to maintain the gradual typing guarantee for untyped attributes. ```python class Message: data = None def __init__(self, title): self.title = title def receive(msg: Message): reveal_type(msg.data) # Unknown | None msg = Message("Favorite color") msg.data = {"color": "blue"} ``` -------------------------------- ### Report non-callable __init_subclass__ methods Source: https://docs.astral.sh/ty/reference/rules Checks for class definitions with non-callable __init_subclass__ methods or attributes. Subclassing such a class will raise a TypeError at runtime. ```python class Super: __init_subclass__ = None class Sub(Super): ... # error: [non-callable-init-subclass] ``` -------------------------------- ### Narrow types using intersection types Source: https://docs.astral.sh/ty/features/type-system Demonstrates how intersection types (A & B) allow access to members of both types after narrowing. ```python def output_as_json(obj: Serializable) -> str: if isinstance(obj, Versioned): reveal_type(obj) # reveals: Serializable & Versioned return str({ "data": obj.serialize_json(), "version": obj.version }) else: return obj.serialize_json() ``` -------------------------------- ### Detect possibly missing import Source: https://docs.astral.sh/ty/reference/rules Flags imports that may fail at runtime if the module or name is not available. ```python # module.py import datetime if datetime.date.today().weekday() != 6: a = 1 # main.py from module import a # ImportError: cannot import name 'a' from 'module' ``` -------------------------------- ### Run in watch mode Source: https://docs.astral.sh/ty/type-checking Enables incremental checking that automatically re-runs when files are modified. ```bash ty check --watch ``` -------------------------------- ### Using Sequence for Read-Only Collections in ty Source: https://docs.astral.sh/ty/reference/typing-faq Adapt function signatures to accept `Sequence` for read-only collections to avoid type errors when dealing with immutable data structures. ```python media_entries = [Directory("Pictures"), Directory("Videos")] # still a type-check error, but should be fine in principle (no mutation occurs) size = total_size_bytes(media_entries) ``` -------------------------------- ### Fixing invalid legacy positional parameters Source: https://docs.astral.sh/ty/reference/rules Demonstrates the incorrect use of legacy positional-only parameters and provides valid alternatives for both older and modern Python versions. ```python def f(x, __y): # Error: `__y` is not considered positional-only pass ``` ```python def f(__x, __y): # If you need compatibility with Python <=3.7 pass ``` ```python def f(x, y, /): # Python 3.8+ syntax pass ``` -------------------------------- ### Configure ty Rules in Zed Source: https://docs.astral.sh/ty/reference/editor-settings Configure ty's rules for the Zed editor. This JSON structure is used within Zed's LSP settings. ```json { "lsp": { "ty": { "settings": { "configuration": { "rules": { "unresolved-reference": "warn" } } } } } } ``` -------------------------------- ### Invalid Type Arguments (Legacy) Source: https://docs.astral.sh/ty/reference/rules Demonstrates errors when providing type arguments that do not satisfy constraints or bounds for legacy type variables. ```python from typing import Generic, TypeVar T1 = TypeVar('T1', int, str) T2 = TypeVar('T2', bound=int) class Foo1(Generic[T1]): ... class Foo2(Generic[T2]): ... Foo1[bytes] # error: bytes does not satisfy T1's constraints Foo2[str] # error: str does not satisfy T2's bound ``` -------------------------------- ### Override rule severity Source: https://docs.astral.sh/ty/reference/configuration Merge custom rule severities with global rules for specific file sets. ```toml [[tool.ty.overrides]] include = ["src"] [tool.ty.overrides.rules] possibly-unresolved-reference = "ignore" ``` ```toml [[overrides]] include = ["src"] [overrides.rules] possibly-unresolved-reference = "ignore" ```