
Astral 发布 ty 1.0:用 Rust 写成的极速 Python 类型检查器
来源标题:Ty 1.0: an extremely fast Python type checker and language server
Astral 宣布推出用 Rust 编写的 Python 类型检查器和语言服务器 ty 1.0,可作为 mypy、Pyright、Pyrefly 的替代方案。ty 已成为 OpenAI 默认且部署最广的类型检查器,覆盖数百万行关键 Python 代码,内部迁移后中位速度提升 24 倍、峰值内存下降 73%。在 18 个生态项目基准测试中,ty 在 16 个项目上是最快的类型检查器。
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
TL;DR: ty is an extremely fast Python type checker and language server, written in Rust, and designed as an alternative to tools like mypy, Pyright, and Pyrefly.
Today, we're announcing the 1.0 release of ty.
ty is now the default and most widely-deployed type checker at OpenAI, providing coverage for many millions of lines of critical Python. Internally, migrating to ty resulted in a median 24x speedup and 73% reduction in peak memory usage.
We’re ready to recommend it for production use, for all users.
At Astral, we build high-performance developer tools for the Python ecosystem. We're best known for uv, our Python package manager, and Ruff, our linter and formatter.
Today, we're announcing the 1.0 release of ty, an extremely fast Python type checker and language server, written in Rust.
You can install ty today with uv tool install ty@latest, or via our VS Code extension.
Like the rest of the Astral toolchain, ty was built with an obsessive focus on performance.
Mean time to type check each project on the command-line, without caching (M3 Max).Show 14 more projects
In our benchmarks, ty was the fastest type checker on 16 out of 18 ecosystem projects: 1.46x faster than Pyrefly and 3.56x faster than Zuban (both written in Rust), by geometric mean.
ty’s architecture is built around "incrementality", which makes live updates extremely fast in the context of an editor or long-lived process. (In the future, we plan to leverage this incrementality to power workflows beyond the editor.)
Mean time to update diagnostics for open files after an edit (M3 Max).Show 13 more projects
In our editor benchmarks, ty was the fastest language server on 14 out of 17 ecosystem projects (7.73x faster than Pyrefly, and 3.22x faster than Zuban).
ty has grown rapidly over the past few months (despite its Beta status), with adoption in widely used projects like FastAPI and tox.
Distribution file downloads in October 2025 and October 2026, from PyPI’s public dataset.
In a November audit of the 25,000 most-downloaded PyPI packages, 11.6% of repositories with a type checker used ty, placing it third behind mypy and Pyright. Among those repositories created in the last year, 22.6% used ty, 26.0% used Pyright, and 62.9% used mypy.
ty takes a novel approach to Python typing based on gradual and set-theoretic typing. It’s our belief that this foundation will enable us to build more than a “faster type checker.” We want to build a better type checker, and one that can co-evolve with Python’s type system.
On the Python typing conformance suite, an imperfect proxy for real-world correctness, ty now records just 14 false positives and 13 false negatives, down from 224 and 405 at the Beta release. (For comparison, mypy reports 190 false positives and 109 false negatives.)
The 1.0 release includes extensive improvements to core type checking, including a novel generics solver and support for extensive bidirectional inference. Of the eight type checkers we tested, only ty both reported the misspelled key below and accepted the function after we corrected it.
podium.pyPlay
1from typing import TypedDict
4class Runner(TypedDict):
5 name: str
6 seconds: float
9def podium(runners: list[Runner]) -> list[Runner]:
10 ranked = sorted(
11 [*runners, {"name": "Ada", "seconds": 53.2}],
12 key=lambda runner: runner["second"],
13 )
14 return ranked[:3]
Runner defines a field named seconds.The list gives Ada’s dictionary the expected type Runner.The sort key receives a Runner, so ty can check the key.ty suggests replacing "second" with "seconds".
$ ty check podium.py
error[invalid-typed-dict-key]: Unknown key "second" for TypedDict Runner
--> podium.py:12:35
|
12 | key=lambda runner: runner["second"],
| ------ ^^^^^^^^ Did you mean "seconds"?
| |
| TypedDict Runner
help: Replace with "seconds"
Found 1 diagnostic
ty infers that Ada’s dictionary is a Runner, just like the other entries. It carries that type into the sort key, where it catches "second" and suggests "seconds".
For a more extreme example, consider satisfies_all, which conjoins an arbitrary number of predicates. ty infers that valid_batch needs an input that has a length and yields integers, accepting [1, 2, 3] and rejecting iter([1, 2, 3]).
batches.pyPlay
1from collections.abc import Callable, Iterable, Sized
3def satisfies_all[T](
4 *predicates: Callable[[T], bool],
- -> Callable[[T], bool]:
6 return lambda x: all(p(x) for p in predicates)
8def large_enough(batch: Sized) -> bool:
9 return len(batch) >= 3
11def all_positive(batch: Iterable[int]) -> bool:
12 return all(n > 0 for n in batch)
14valid_batch = satisfies_all(large_enough, all_positive)
15valid_batch([1, 2, 3]) # True
16valid_batch(iter([1, 2, 3])) # TypeError: the iterator has no length
The first predicate needs a value with a length.The second needs a value that yields integers.valid_batch now expects Sized & Iterable[int].A list of integers meets both requirements.The iterator yields integers but has no length.
$ ty check batches.py
error[invalid-argument-type]: Argument is incorrect
--> batches.py:16:13
|
16 | valid_batch(iter([1, 2, 3])) # TypeError: the iterator has no length
| ^^^^^^^^^^^^^^^ Expected Sized & Iterable[int], found Iterator[int]
The list meets both requirements. The iterator yields integers but has no len, so ty flags the second call.
Mypy infers Never for the conjoined predicates’ input and rejects both calls. Pyright infers Sized from large_enough and flags the call to satisfies_all. Pyrefly infers Sized | Iterable[int] and accepts the iterator, which fails at runtime.
With the 1.0 release, ty now includes built-in support for foundational Python libraries like Pydantic, Django, pytest, and attrs.
options.pyPlay
1from pathlib import Path
2from pydantic import BaseModel, Field
4class Options(BaseModel):
5 output: Path
6 simulate: bool = Field(
7 default=False,
8 strict=True,
9 alias="dry_run",
10 )
12Options(output="./exports", dry_run=True)
13Options(output="./exports", dry_run="true")
14Options(output="./exports", simulate=True)
The constructor takes dry_run for this field.Pydantic converts the string to a Path.The strict field requires a bool.Pydantic discards this argument and keeps the default.
$ ty check options.py
error[invalid-argument-type]: Argument is incorrect
--> options.py:13:29
|
13 | Options(output="./exports", dry_run="true")
| ^^^^^^^^^^^^^^ Expected bool, found Literal["true"]
warning[pydantic-discarded-extra-argument]: Extra argument simulate is discarded by Pydantic
--> options.py:14:8
|
14 | Options(output="./exports", simulate=True)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ty accepts the path string that Pydantic converts to a Path. It flags the string passed to the strict boolean field and warns about simulate=True because the constructor expects dry_run for that field.
Return type inference #
We’ve also added opt-in return type inference for functions without return annotations. In the example below, decode checks that a log record has an id before returning it. ty carries that information to the caller, so it accepts record.id.
logs.pyPlay
1import json
2import logging
5def decode(line: str):def decode(line: str):
6 record = logging.makeLogRecord(json.loads(line))
7 if not hasattr(record, "id"):
8 raise ValueError("Missing record id")
9 return record
12def show(line: str) -> None:
13 record = decode(line)
14 print(record.id, record.getMessage())
By default, ty treats the result of decode as Unknown.With record typed as Unknown, ty permits both attribute accesses.With return type inference enabled, ty follows the id check.The id check holds on every successful return.Inferred return type: LogRecord with an id attribute of type object.
$ ty check logs.py
All checks passed!
$ ty check -c 'analysis.return-type-inference="always"' logs.py
All checks passed!
With return type inference enabled, ty carries both the LogRecord type and the id check from decode to its caller.
With return type inference enabled, Pyright, Pyrefly, and Zuban infer LogRecord and flag the access to record.id. Mypy infers Any.
In the Beta announcement, we highlighted our best-in-class diagnostic system and editor integrations. A single ty diagnostic can connect a warning to its cause, even across files, and suggest a fix.
quiz.pyPlay
1from dataclasses import dataclass
4@dataclass
5class QuizResults:
6 scores: tuple[int]
8 def average(self) -> float | None:
9 if self.scores:
10 return sum(self.scores) / len(self.scores)
11 return None
The check is meant to handle a quiz with no scores.The annotation requires exactly one score, so the check is always true.The branch for an empty tuple is unreachable.Use tuple[int, ...] to allow an empty tuple.
$ ty check quiz.py
warning[redundant-condition]: A 1-element tuple is always truthy
--> quiz.py:9:12
|
6 | scores: tuple[int]
| ----------
| |
| Inferred as a 1-element tuple due to this annotation
| Did you mean tuple[int, ...]?
7 |
8 | def average(self) -> float | None:
9 | if self.scores:
| ^^^^^^^^^^^ Inferred type tuple[int] is always truthy
10 | return sum(self.scores) / len(self.scores)
11 | return None
| ----------- This following statement is unreachable
Found 1 diagnostic
tuple[int] describes a tuple with exactly one element, so ty can trace the unreachable return None back to the annotation. Use tuple[int, ...] for a tuple that can be empty.
In 1.0, we also support applying those fixes automatically via ty check --fix.
span.pyPlay
1import typing
4class Span(typing.NamedTuple):
5 start: int
6 end: int
8 def midpoint(self) -> int:
9 return typing.cast(int, self.start + self.end) // 2 return (self.start + self.end) // 2 return typing.cast(int, self.start + self.end) // 2
Adding two integers already produces an int.ty identifies the redundant cast.The sum must stay grouped before floor division.The fixed expression adds first, then divides.The next check passes.
$ ty check span.py
warning[redundant-cast]: Value is already of type int
$ ty check --fix span.py
- return typing.cast(int, self.start + self.end) // 2
- return (self.start + self.end) // 2
Found 1 diagnostic (1 fixed, 0 remaining).
$ ty check span.py
All checks passed!
Both endpoints are integers, so the cast in Span.midpoint is redundant. ty check --fix removes it and keeps the parentheses around the sum, preserving the order of operations.
Migration support #
When migrating an existing project, you can now run ty check --add-ignore to add suppression comments in one pass.
Alternatively, configure a diagnostic baseline and run ty check --update-baseline to record existing diagnostics in a separate file. Commit that file, and CI can flag new errors while you fix existing diagnostics over time.
invoice.pyPlay
1def invoice_total(cents: int) -> int:
2 return str(cents)
invoice_total("1200")
The function promises an integer and returns a string.Save the existing error with ty check --update-baseline. The next check passes.Add a call in the same file and run ty check again.
Saved in ty-baseline.jsonNo saved diagnosticsLine 2Expected int, returned str.Line 2Expected int, returned str.
Reported by ty checkLine 2Expected int, returned str.All checks passedLine 5Expected int, got str.
The baseline saves individual diagnostics. A new error in the same file still fails the check.
Script support #
In our uv and ty integration announcement, we introduced support for type checking standalone Python scripts that declare their dependencies and Python requirements through inline metadata (PEP 723).
By integrating with uv, ty can automatically prepare a separate environment for each script, allowing you to check an entire project and its scripts together, even when they require different Python versions or conflicting dependencies. The same integration pow
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。
