### Run ty without installation using uvx Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Use uvx to quickly get started with ty without a formal installation. ```shell uvx ty ``` -------------------------------- ### Install ty globally with uv Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Install ty globally on your system using the `uv tool install` command. ```shell uv tool install ty@latest ``` -------------------------------- ### Project Directory Structure Example Source: https://github.com/astral-sh/ty/blob/main/docs/modules.md An example of a project layout where source code is located in an app directory. ```text example-pkg ├── README.md ├── pyproject.toml └── app └── example_pkg └── __init__.py ``` -------------------------------- ### Install ty in Docker Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Install ty in a Docker container by copying the binary from the official Astral ty image. ```dockerfile COPY --from=ghcr.io/astral-sh/ty:latest /ty /bin/ ``` -------------------------------- ### Start Ty Language Server Source: https://github.com/astral-sh/ty/blob/main/docs/editors.md Use this command to start the Ty language server. Refer to your editor's documentation for instructions on connecting to an LSP server. ```shell ty server ``` -------------------------------- ### Install ty with pip Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Install ty into your current Python environment using pip. ```shell pip install ty ``` -------------------------------- ### Inspect ty installer script on Windows Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Inspect the contents of the ty standalone installer script before execution on Windows using `irm` and `more`. ```pwsh-session PS> powershell -c "irm https://astral.sh/ty/install.ps1 | more" ``` -------------------------------- ### Install ty globally with mise Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Install ty globally using the mise version manager. ```shell mise install ty ``` -------------------------------- ### Install ty on Windows using PowerShell and irm Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Download and execute the ty standalone installer script on Windows using PowerShell's `irm` cmdlet. Ensure your execution policy allows script execution. ```pwsh-session PS> powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/ty/install.ps1 | iex" ``` -------------------------------- ### Install ty on macOS and Linux using curl Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Download and execute the ty standalone installer script using curl. ```console $ curl -LsSf https://astral.sh/ty/install.sh | sh ``` -------------------------------- ### Install ty on macOS and Linux using wget Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Download and execute the ty standalone installer script using wget if curl is not available. ```console $ wget -qO- https://astral.sh/ty/install.sh | sh ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/astral-sh/ty/blob/main/CONTRIBUTING.md Install development dependencies using uv and prek hooks for automatic validation on commit. ```shell uv run --only-group dev --locked prek install ``` -------------------------------- ### Inspect ty installer script on macOS and Linux Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Inspect the contents of the ty standalone installer script before execution using `curl` and `less`. ```console $ curl -LsSf https://astral.sh/ty/install.sh | less ``` -------------------------------- ### Install ty globally with pipx Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Install ty globally using the pipx package manager. ```shell pipx install ty ``` -------------------------------- ### Example Python configuration for Ty Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This TOML snippet shows the configuration for the Python version used by Ty. ```toml [environment] python-version = "3.12" ``` -------------------------------- ### Install a specific version of ty on Windows Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Request a specific version of ty during installation on Windows by including the version number in the download URL. ```pwsh-session PS> powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/ty/0.0.56/install.ps1 | iex" ``` -------------------------------- ### Install a specific version of ty on macOS and Linux Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Request a specific version of ty during installation by including the version number in the download URL. ```console $ curl -LsSf https://astral.sh/ty/0.0.56/install.sh | sh ``` -------------------------------- ### Explain Ty Help Source: https://github.com/astral-sh/ty/blob/main/docs/reference/cli.md Prints help messages for Ty commands. You can specify a subcommand to get its specific help information. ```bash ty explain help [COMMAND] ``` -------------------------------- ### Upgrade globally installed ty with uv Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Update a globally installed ty package using `uv tool upgrade`. ```shell uv tool upgrade ty ``` -------------------------------- ### Configure Extra Paths in ty.toml Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Specify custom paths for module resolution in ty.toml. Use this for modules not installed conventionally. ```toml [environment] extra-paths = ["./shared/my-search-path"] ``` -------------------------------- ### Unsupported Operator Example Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Demonstrates an unsupported operation between two instances of a custom class, which will result in a TypeError. ```python class A: ... # TypeError: unsupported operand type(s) for +: 'A' and 'A' A() + A() # error ``` -------------------------------- ### Unused Awaitable Example Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Shows a coroutine being called but not awaited, which will trigger a RuntimeWarning. The correct usage with 'await' is also shown. ```python async def fetch_data() -> str: return "data" async def main() -> None: # Warning: coroutine is not awaited fetch_data() # error await fetch_data() # OK ``` -------------------------------- ### Configure Multiple Source Roots for Ty in Monorepo Source: https://github.com/astral-sh/ty/blob/main/docs/reference/typing-faq.md Define multiple source directories for Ty in a monorepo setup using pyproject.toml. This treats all specified packages as a single project. ```toml [tool.ty.environment] root = ["packages/package-a", "packages/package-b"] ``` -------------------------------- ### ty check --extra-search-path option Source: https://github.com/astral-sh/ty/blob/main/docs/reference/cli.md Add an additional path for module resolution in 'ty check'. Useful for unconventional module installations. ```bash ty check --extra-search-path ``` -------------------------------- ### Upgrade ty with pipx Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Update a globally installed ty package using `pipx upgrade`. ```shell pipx upgrade ty ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/astral-sh/ty/blob/main/CONTRIBUTING.md Run the documentation development server using uvx and mkdocs. The documentation will be available at http://127.0.0.1:8000/ty/. ```shell uvx --with-requirements docs/requirements.txt -- mkdocs serve -f mkdocs.yml ``` -------------------------------- ### Configure Project Root Directories Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Specify multiple directories to search for first-party modules. Paths are searched in priority order. If unspecified, Ty attempts to detect common project layouts. ```toml [tool.ty.environment] # Multiple directories (priority order) root = ["./src", "./lib", "./vendor"] ``` ```toml [environment] # Multiple directories (priority order) root = ["./src", "./lib", "./vendor"] ``` -------------------------------- ### Main ty CLI Usage Source: https://github.com/astral-sh/ty/blob/main/docs/reference/cli.md The basic command structure for using the 'ty' CLI. ```bash ty ``` -------------------------------- ### Enable Auto-Import Suggestions (Zed) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure ty to include auto-import suggestions in code completions for Zed. ```json { "lsp": { "ty": { "settings": { "completions": { "autoImport": true } } } } } ``` -------------------------------- ### Configure include and exclude paths Source: https://github.com/astral-sh/ty/blob/main/docs/exclusions.md Define directories to include or exclude from file discovery using project configuration files. ```toml [tool.ty.src] include = ["src", "tests"] exclude = ["src/generated"] ``` ```toml [src] include = ["src", "tests"] exclude = ["src/generated"] ``` -------------------------------- ### Validate static_assert arguments Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This Python code shows examples where static_assert fails because its argument is not statically known to be true. ```python from ty_extensions import static_assert # evaluates to `False` static_assert(1 + 1 == 3) # error # does not have a statically known truthiness static_assert(int(2.0 * 3.0) == 6) # error ``` -------------------------------- ### Display help for the 'ty' CLI Source: https://github.com/astral-sh/ty/blob/main/docs/reference/cli.md Use this command to view the general help message for the 'ty' CLI. It provides an overview of available commands and their usage. ```bash ty help [COMMAND] ``` -------------------------------- ### Configure Extra Paths in pyproject.toml Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Specify custom paths for module resolution in pyproject.toml. Use this for modules not installed conventionally. ```toml [tool.ty.environment] extra-paths = ["./shared/my-search-path"] ``` -------------------------------- ### Configure rule levels via command line Source: https://github.com/astral-sh/ty/blob/main/docs/rules.md Use flags to set specific rules to error, warn, or ignore status during execution. ```shell 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` ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/astral-sh/ty/blob/main/CONTRIBUTING.md After cloning, initialize and update all git submodules recursively. ```shell git submodule update --init --recursive ``` -------------------------------- ### Incorrect Legacy Positional-Only Parameter Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This example shows a function where `__y` is intended to be positional-only but is not recognized as such due to incorrect legacy syntax. ```python # `__y` is not considered positional-only def f(x, __y): # error pass ``` -------------------------------- ### Configure Override Rules with Inclusions Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Specify file and directory patterns to include for an override. If not specified, defaults to matching all files (`**`). ```toml [[tool.ty.overrides]] include = [ "src", "tests", ] ``` ```toml [[overrides]] include = [ "src", "tests", ] ``` -------------------------------- ### Unresolved Import Statement Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Checks for import statements where the module cannot be resolved, preventing runtime ModuleNotFoundError. Ensure all imported modules are installed and accessible. ```python # ModuleNotFoundError: No module named 'foo' import foo # error ``` -------------------------------- ### Configure Custom Typeshed Path Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Provide an optional path to a custom typeshed directory on disk for standard-library types. Falls back to vendored typeshed stubs if not provided. ```toml [tool.ty.environment] typeshed = "/path/to/custom/typeshed" ``` ```toml [environment] typeshed = "/path/to/custom/typeshed" ``` -------------------------------- ### Specify ty configuration file in Neovim (<0.11) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure the path to ty's configuration file using the lspconfig plugin for Neovim versions prior to 0.11. ```lua require('lspconfig').ty.setup({ settings = { ty = { configurationFile = "./.config/ty.toml" }, }, }) ``` -------------------------------- ### Invalid string annotation syntax Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Use a valid Python expression within the string literal for forward references. This example shows an incorrect usage. ```python def foo() -> "instance of C": # error return 42 class C: ... ``` -------------------------------- ### Enable Auto-Import Suggestions (Neovim) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure ty to include auto-import suggestions in code completions for Neovim. Supports versions >=0.11 and <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, }, }, }, }) ``` -------------------------------- ### Subclassing Dataclass with Order=True Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This example demonstrates a class inheriting from a dataclass where `order=True`. This pattern is flagged because it can cause `TypeError` at runtime when comparing instances of the parent and child classes. ```python from dataclasses import dataclass @dataclass(order=True) class Parent: value: int class Child(Parent): # error pass # At runtime, this raises TypeError: # Child(1) < Parent(2) ``` -------------------------------- ### Enable fish shell autocompletion for ty Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Add ty shell autocompletion for fish to your `~/.config/fish/completions/ty.fish` file. ```fish echo 'ty generate-shell-completion fish | source' > ~/.config/fish/completions/ty.fish ``` -------------------------------- ### Python Type Variable Bound Examples Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Illustrates invalid type variable bounds where the bound itself references a type variable. Type variable bounds must be concrete types. ```python from typing import TypeVar # error: [invalid-type-variable-bound] RecursiveT = TypeVar("RecursiveT", bound=list["RecursiveT"]) U = TypeVar("U") # error: [invalid-type-variable-bound] BoundT = TypeVar("BoundT", bound=U) def f[T: list[T]](): ... # error: [invalid-type-variable-bound] def g[U, T: U](): ... # error: [invalid-type-variable-bound] ``` -------------------------------- ### Configure Project Root Source: https://github.com/astral-sh/ty/blob/main/docs/modules.md Configuration settings to define the project root directory when using a non-standard layout. ```toml [tool.ty.environment] root = ["./app"] ``` ```toml [environment] root = ["./app"] ``` -------------------------------- ### Runtime Error Example from Invariance Violation Source: https://github.com/astral-sh/ty/blob/main/docs/reference/typing-faq.md Shows a potential runtime error when code expects `Directory` objects but receives a `File` object due to a prior invariance violation. ```Python for directory in directories: directory.children() # runtime: 'File' object has no attribute 'children' ``` -------------------------------- ### Configure ty rules in Neovim (<0.11) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure ty's rules using the lspconfig plugin for Neovim versions prior to 0.11. ```lua require('lspconfig').ty.setup({ settings = { ty = { configuration = { rules = { ["unresolved-reference"] = "warn" } } } }, }) ``` -------------------------------- ### Enum member with explicit type annotation (error) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This example shows an enum member 'DOG' with an explicit type annotation 'int', which is flagged as an error by the rule. Enum members should not be annotated. ```python from enum import Enum class Pet(Enum): CAT = 1 # OK # enum members should not be annotated DOG: int = 2 # error ``` -------------------------------- ### Run ty with uvx Source: https://github.com/astral-sh/ty/blob/main/docs/index.md Use uvx to quickly run ty for checking Python files. ty checks all Python files in the working directory or project by default. ```shell uvx ty check ``` -------------------------------- ### Build Python Package Source: https://github.com/astral-sh/ty/blob/main/CONTRIBUTING.md Build the Python package using uv. Maturin is used as the build backend. ```shell uv build ``` -------------------------------- ### Valid and invalid TypeAliasType creation Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This example illustrates the correct and incorrect ways to create `TypeAliasType` instances. It shows that the name provided to `TypeAliasType` must be a string literal, not a variable or function call. ```python from typing import TypeAliasType def get_name() -> str: return "NewAlias" IntOrStr = TypeAliasType("IntOrStr", int | str) # okay # TypeAliasType name must be a string literal NewAlias = TypeAliasType(get_name(), int) # error ``` -------------------------------- ### Corrected enum member without annotation Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This example demonstrates the correct way to define enum members without explicit type annotations, allowing type checkers to infer the literal type. ```python from enum import Enum class Pet(Enum): CAT = 1 DOG = 2 ``` -------------------------------- ### Invoke ty using uv run Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md After adding ty as a dependency, use `uv run` to invoke it. ```shell uv run ty ``` -------------------------------- ### Type Assertion Failure in Python Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This example shows the correct and incorrect usage of `assert_type`. The incorrect usage occurs when the actual type of a variable does not match the type asserted in the `assert_type` call, leading to an error. ```python from typing import assert_type def _(x: int): assert_type(x, int) # fine # Actual type does not match asserted type assert_type(x, str) # error ``` -------------------------------- ### Set all rules to error in configuration files Source: https://github.com/astral-sh/ty/blob/main/docs/rules.md Configure all rules to a specific level globally within the configuration file. ```toml [tool.ty.rules] all = "error" ``` ```toml [rules] all = "error" ``` -------------------------------- ### Python Invalid Attribute Access Examples Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Demonstrates correct and incorrect assignments to class variables and instance-only variables in Python. Use this snippet to understand the rule's behavior with different assignment scenarios. ```python from typing import ClassVar class C: instance_var: int class_var: ClassVar[int] = 1 def __init__(self): # instance variable declared in the class body self.instance_var = 42 # instance-only variable not declared in the class body self.instance_only_var: int = 42 C.class_var = 3 # okay C.instance_var = 56 # okay C().instance_var = 72 # okay C().instance_only_var = 100 # okay # Cannot assign to class variable from instance C().class_var = 3 # error # Cannot assign to instance-only variable from class C.instance_only_var = 56 # error ``` -------------------------------- ### Enable ty Language Server in Neovim (<0.11) Source: https://github.com/astral-sh/ty/blob/main/docs/editors.md Configure older versions of Neovim (<0.11) to use ty as a language server via nvim-lspconfig. This requires an older version of the nvim-lspconfig extension. ```lua require('lspconfig').ty.setup({ settings = { ty = { -- ty language server settings go here } } }) ``` -------------------------------- ### Configure Ty Import Strategy in VS Code Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Set the strategy for loading the ty executable. Use 'useBundled' to ensure the extension's bundled version is used. ```json { "ty.importStrategy": "useBundled" } ``` -------------------------------- ### Disallow Underscore Prefix for NamedTuple Fields Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Field names in NamedTuple classes cannot start with an underscore. This rule prevents potential naming conflicts and ensures valid field definitions, avoiding runtime ValueErrors. ```python >>> from typing import NamedTuple >>> class Foo(NamedTuple): ... _bar: int ValueError: Field names cannot start with an underscore: '_bar' ``` -------------------------------- ### Enable Auto-Import Suggestions Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure ty to include auto-import suggestions in code completions. Allows completion of symbols not currently in scope. ```json { "ty.completions.autoImport": true } ``` -------------------------------- ### Assert type with unspellable subtype Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This example demonstrates an assert_type() call where the actual type is an unspellable subtype of the asserted type. This occurs when ty infers a more precise type than can be expressed in user annotations, leading to a potential type assertion failure. ```python from typing import assert_type def _(x: int): assert_type(x, int) # fine if x: # the actual type is `int & ~AlwaysFalsy`, # which excludes types like `Literal[0]` # error: [assert-type-unspellable-subtype] assert_type(x, int) ``` -------------------------------- ### Home Assistant Benchmark Results Source: https://github.com/astral-sh/ty/blob/main/BENCHMARKS.md This snippet presents benchmark results for 'ty' and other tools on the 'Home Assistant' project. It highlights performance differences and comparative speeds. ```text homeassistant ------------- Benchmark 1: ty Time (mean ± σ): 1.812 s ± 0.033 s [User: 23.009 s, System: 2.224 s] Range (min … max): 1.782 s … 1.873 s 10 runs Warning: Ignoring non-zero exit code. Benchmark 2: Pyrefly Time (mean ± σ): 2.550 s ± 0.039 s [User: 23.491 s, System: 4.450 s] Range (min … max): 2.502 s … 2.624 s 10 runs Warning: Ignoring non-zero exit code. Benchmark 3: mypy Time (mean ± σ): 24.601 s ± 0.141 s [User: 45.118 s, System: 4.172 s] Range (min … max): 24.340 s … 24.846 s 10 runs Benchmark 4: Pyright Time (mean ± σ): 23.410 s ± 0.483 s [User: 323.789 s, System: 22.983 s] Range (min … max): 22.596 s … 23.994 s 10 runs Warning: Ignoring non-zero exit code. Summary ty ran 1.41 ± 0.03 times faster than Pyrefly 12.92 ± 0.36 times faster than Pyright 13.57 ± 0.26 times faster than mypy ------------------------------------------------------------------------------- ``` -------------------------------- ### Python Type Guard Definition Examples Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Demonstrates incorrect definitions for type guard functions. Type guards must have at least one positional argument. This includes cases with no parameters, only keyword-only parameters, variadic arguments, or only `self`/`cls` in methods. ```python from typing import TypeIs # no parameter def f() -> TypeIs[int]: # error return True # no positional arguments allowed def f(*, v: object) -> TypeIs[int]: # error return True # expected variadic arguments def f(*args: object) -> TypeIs[int]: # error return True class C: # only positional argument is `self` def f(self) -> TypeIs[int]: # error return True ``` -------------------------------- ### Type Checking PEP 723 Inline-Metadata Scripts with ty Source: https://github.com/astral-sh/ty/blob/main/docs/reference/typing-faq.md Use this command to type check a single Python script that includes PEP 723 inline metadata. The `--with-requirements` flag ensures that dependencies specified in the script's header are installed. ```bash uvx --with-requirements script.py ty check script.py ``` -------------------------------- ### Specify ty configuration file in Neovim (>=0.11) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure the path to ty's configuration file using the Lua API for Neovim versions 0.11 and later. ```lua vim.lsp.config('ty', { settings = { ty = { configurationFile = "./.config/ty.toml" }, }, }) ``` -------------------------------- ### Include files and directories in ty.toml Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Specify files and directories to include for type checking in ty.toml. This setting is overridden by 'exclude'. ```toml [src] include = [ "src", "tests", ] ``` -------------------------------- ### Abstract method in final class example Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This snippet demonstrates a final class 'Derived' that inherits from an abstract base class 'Base' but fails to implement the abstract method 'method'. This violates the rule, as a final class cannot be subclassed to implement missing abstract methods. ```python from abc import ABC, abstractmethod from typing import final class Base(ABC): @abstractmethod def method(self) -> int: ... @final # `Derived` does not implement `method` class Derived(Base): # error pass ``` -------------------------------- ### Configure Ty Log File in Neovim Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Set the log file path for the Ty language server in Neovim. This is configured within the 'init_options' for the LSP client. ```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', }, }) ``` -------------------------------- ### Enable ty Language Server in Neovim (>=0.11) Source: https://github.com/astral-sh/ty/blob/main/docs/editors.md Configure Neovim to use ty as a language server using nvim-lspconfig. This snippet shows how to enable the server and optionally configure its settings. ```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') ``` -------------------------------- ### Python Version Conditional Syntax and Symbols Source: https://github.com/astral-sh/ty/blob/main/docs/python-version.md Demonstrates how to use Python 3.10+ syntax like 'match' statements and access version-specific symbols like 'sys.stdlib_module_names'. Shows how to guard newer features with version checks to maintain compatibility with older Python versions. ```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) ``` -------------------------------- ### Configure ty rules in Neovim (>=0.11) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure ty's rules using the Lua API for Neovim versions 0.11 and later. ```lua vim.lsp.config('ty', { settings = { ty = { configuration = { rules = { ["unresolved-reference"] = "warn" } } } }, }) ``` -------------------------------- ### Configure rule levels in configuration files Source: https://github.com/astral-sh/ty/blob/main/docs/rules.md Define rule levels within project configuration files for persistent settings. ```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" ``` -------------------------------- ### Format Markdown Files Source: https://github.com/astral-sh/ty/blob/main/CONTRIBUTING.md Format all markdown files in the repository using Prettier to ensure consistent style. ```shell npx prettier --prose-wrap always --write "**/*.md" ``` -------------------------------- ### Explain Ty Rules Source: https://github.com/astral-sh/ty/blob/main/docs/reference/cli.md Provides explanations for Ty rules. You can specify a particular rule or omit it to explain all rules. The output format can be text or JSON. ```bash ty explain rule [OPTIONS] [RULE] ``` ```bash ty explain rule --output-format json ``` -------------------------------- ### Set project root in ty.toml Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Specify the project root directory in ty.toml using the 'root' option. This option is deprecated in favor of 'environment.root'. ```toml [src] root = "./app" ``` -------------------------------- ### General Benchmark Results for ty Source: https://github.com/astral-sh/ty/blob/main/BENCHMARKS.md This benchmark shows the mean execution time and standard deviation for 'ty' compared to Pyrefly, mypy, and Pyright. It indicates 'ty' is significantly faster than Pyright and mypy, and slightly faster than Pyrefly. ```text Benchmark 1: ty Time (mean ± σ): 1.216 s ± 0.042 s [User: 14.994 s, System: 0.766 s] Range (min … max): 1.157 s … 1.293 s 10 runs Warning: Ignoring non-zero exit code. Benchmark 2: Pyrefly Time (mean ± σ): 1.492 s ± 0.025 s [User: 12.424 s, System: 1.053 s] Range (min … max): 1.451 s … 1.519 s 10 runs Warning: Ignoring non-zero exit code. Benchmark 3: mypy Time (mean ± σ): 28.227 s ± 0.074 s [User: 27.631 s, System: 0.580 s] Range (min … max): 28.137 s … 28.342 s 10 runs Warning: Ignoring non-zero exit code. Benchmark 4: Pyright Time (mean ± σ): 16.885 s ± 0.505 s [User: 231.071 s, System: 9.429 s] Range (min … max): 16.283 s … 17.933 s 10 runs Warning: Ignoring non-zero exit code. Summary ty ran 1.23 ± 0.05 times faster than Pyrefly 13.89 ± 0.63 times faster than Pyright 23.22 ± 0.80 times faster than mypy ``` -------------------------------- ### Black Benchmark Results Source: https://github.com/astral-sh/ty/blob/main/BENCHMARKS.md This snippet shows the benchmark results for 'ty' and other tools on the 'Black' project. It includes mean time, standard deviation, and run counts. ```text black ----- Benchmark 1: ty Time (mean ± σ): 69.5 ms ± 1.6 ms [User: 530.8 ms, System: 34.8 ms] Range (min … max): 65.7 ms … 73.6 ms 40 runs Warning: Ignoring non-zero exit code. Benchmark 2: Pyrefly Time (mean ± σ): 128.3 ms ± 2.5 ms [User: 465.1 ms, System: 53.0 ms] Range (min … max): 123.4 ms … 134.3 ms 23 runs Warning: Ignoring non-zero exit code. Benchmark 3: mypy Time (mean ± σ): 1.316 s ± 0.012 s [User: 1.216 s, System: 0.092 s] Range (min … max): 1.303 s … 1.336 s 10 runs Benchmark 4: Pyright Time (mean ± σ): 1.420 s ± 0.010 s [User: 18.088 s, System: 0.981 s] Range (min … max): 1.404 s … 1.433 s 10 runs Warning: Ignoring non-zero exit code. Summary ty ran 1.85 ± 0.06 times faster than Pyrefly 18.94 ± 0.46 times faster than mypy 20.45 ± 0.49 times faster than Pyright ------------------------------------------------------------------------------- ``` -------------------------------- ### Set all rules to error via command line Source: https://github.com/astral-sh/ty/blob/main/docs/rules.md Apply a global rule level to all checks using the all keyword. ```shell ty check --error all ``` -------------------------------- ### Clone TY Repository Source: https://github.com/astral-sh/ty/blob/main/CONTRIBUTING.md Use this command to clone the TY repository from GitHub. ```shell git clone https://github.com/astral-sh/ty.git ``` -------------------------------- ### Configure Override Rules with Exclusions Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Define file and directory patterns to exclude from an override. Exclude patterns take precedence over include patterns within the same override. Defaults to excluding no files. ```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 ] ``` -------------------------------- ### Enable Elvish shell autocompletion for ty Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Add ty shell autocompletion for Elvish to your `~/.elvish/rc.elv` file. ```elvish echo 'eval (ty generate-shell-completion elvish | slurp)' >> ~/.elvish/rc.elv ``` -------------------------------- ### Configure Python version for experimental syntax Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md Specify the Python version to enable experimental syntax checks. This is useful for testing upcoming language features. ```toml [environment] python-version = "3.14" ``` -------------------------------- ### Ignore virtual environment files Source: https://github.com/astral-sh/ty/blob/main/docs/exclusions.md Create a .gitignore file within a virtual environment directory to prevent ty from emitting diagnostics for those files. ```shell echo "*" > .venv/.gitignore ``` -------------------------------- ### Display Ty Version Source: https://github.com/astral-sh/ty/blob/main/docs/reference/cli.md Displays the current version of Ty. The output format can be specified as plain text or JSON. ```bash ty version [OPTIONS] ``` ```bash ty version --output-format json ``` -------------------------------- ### Specify ty configuration file in Zed Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Set the path to ty's configuration file within the Zed editor's LSP settings. ```json { "lsp": { "ty": { "settings": { "configurationFile": "./.config/ty.toml" } } } } ``` -------------------------------- ### Configure Project Root for Ty Source: https://github.com/astral-sh/ty/blob/main/docs/reference/typing-faq.md Specify non-root source directories for Ty when your code is not in the project root or src/ directory. This is configured in pyproject.toml. ```toml [tool.ty.environment] root = ["./app"] ``` -------------------------------- ### Exclude files and directories in ty.toml Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Configure patterns to exclude files and directories from type checking in ty.toml. Supports .gitignore-like syntax, including negation. ```toml [src] exclude = [ "generated", "*.proto", "tests/fixtures/**", "!tests/fixtures/important.py" # Include this one file ] ``` -------------------------------- ### Enable Function Parentheses Insertion (Zed) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure ty to automatically insert parentheses for completions in Zed. ```json { "lsp": { "ty": { "settings": { "completions": { "completeFunctionParentheses": true } } } } } ``` -------------------------------- ### isort Benchmark Results Source: https://github.com/astral-sh/ty/blob/main/BENCHMARKS.md This snippet shows the benchmark results for 'ty' and other tools on the 'isort' project. It includes performance metrics and comparative speed. ```text isort ----- ``` -------------------------------- ### Add ty as a development dependency using uv Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Add ty as a development dependency to your project using uv. This ensures all developers use the same version. ```shell uv add --dev ty ``` -------------------------------- ### Set ty globally with mise Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Configure mise to use ty globally. ```shell mise use --global ty ``` -------------------------------- ### Configure Ty Log File in Zed Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Define the log file path for the Ty language server within Zed's LSP configuration. ```json { "lsp": { "ty": { "initialization_options": { "logFile": "/path/to/ty.log" } } } } ``` -------------------------------- ### Run Ty Per-Package in Monorepo Source: https://github.com/astral-sh/ty/blob/main/docs/reference/typing-faq.md Execute Ty's check command for 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 ``` -------------------------------- ### Specify ty configuration file in VS Code Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Set the path to a custom ty.toml configuration file in VS Code. This overrides any discovered configurations. ```json { "ty.configurationFile": "./.config/ty.toml" } ``` -------------------------------- ### Conditional Reachability for Dependency Version Compatibility Source: https://github.com/astral-sh/ty/blob/main/docs/features/type-system.md Shows how ty's reachability analysis allows code to be type-checked against different dependency versions by evaluating version-specific conditions at type-checking time. ```python import pydantic from pydantic import BaseModel PYDANTIC_V2 = pydantic.__version__.startswith("2.") class Person(BaseModel): name: str def to_json(person: Person): if PYDANTIC_V2: return person.model_dump_json() # no error here when checking with 1.x else: return person.json() ``` -------------------------------- ### Enable Zsh shell autocompletion for ty Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Add ty shell autocompletion for Zsh to your `~/.zshrc` file. ```bash echo 'eval "$(ty generate-shell-completion zsh)"' >> ~/.zshrc ``` -------------------------------- ### Correct string annotation syntax Source: https://github.com/astral-sh/ty/blob/main/docs/reference/rules.md This demonstrates the correct way to use string literals for forward references, ensuring the string can be parsed as a Python expression. ```python def foo() -> "C": return C() class C: ... ``` -------------------------------- ### Enable PowerShell/pwsh shell autocompletion for ty Source: https://github.com/astral-sh/ty/blob/main/docs/installation.md Add ty shell autocompletion for PowerShell/pwsh to your `$PROFILE` file. This script ensures the profile file exists and appends the autocompletion command. ```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' ``` -------------------------------- ### Enable Function Parentheses Insertion (Neovim) Source: https://github.com/astral-sh/ty/blob/main/docs/reference/editor-settings.md Configure ty to automatically insert parentheses for completions in Neovim. Supports versions >=0.11 and <0.11. ```lua -- Neovim >=0.11: vim.lsp.config('ty', { settings = { ty = { completions = { completeFunctionParentheses = true, }, }, }, }) -- Neovim <0.11: require('lspconfig').ty.setup({ settings = { ty = { completions = { completeFunctionParentheses = true, }, }, }, }) ``` -------------------------------- ### Include files and directories in pyproject.toml Source: https://github.com/astral-sh/ty/blob/main/docs/reference/configuration.md Specify files and directories to include for type checking in pyproject.toml. This setting is overridden by 'exclude'. ```toml [tool.ty.src] include = [ "src", "tests", ] ```