Ty 1.0:一个极快的 Python 类型检查器和语言服务器
Ty 1.0: an extremely fast Python type checker and language server

原始链接: https://astral.sh/blog/ty-1.0

Astral 宣布了 ty 1.0,这是一款基于 Rust 的快速 Python 类型检查器与语言服务器,定位为 mypy、Pyright 和 Pyrefly 的替代品。它已可用于生产环境,现已成为 OpenAI 的默认类型检查器, reportedly 达到中位数 24 倍加速,峰值内存降低 73%。基准测试显示 ty 在大多数被测项目中最快,且在 PyPI 包中的采用率正在增长。ty 使用渐进式与集合论类型系统,改进了泛型与双向推断,内置支持 Pydantic、Django、pytest 和 attrs,提供可选的返回类型推断、带自动修复的强诊断、迁移助手、通过 uv 进行 PEP 723 脚本检查,以及可配置的渐进式类型选项。它还支持高级检查,例如不健全返回警告。Astral 计划推出未来类型感知工具。

Hacker News 讨论了 Astral 发布的 Ty 1.0,这是一款极快的 Python 类型检查器和语言服务器。评论者向团队表示祝贺,并回忆起 1.0 之前的可靠使用。一些人将 Ty 与 Pyrefly 进行比较,并询问 Ruff 和 UV 何时达到 1.0。其他人则提出生态系统控制担忧:OpenAI 拥有 Astral,Microsoft 拥有 Pyright/TypeScript 工具,Meta 支持 Pyrefly,企业越来越寻求影响开发者生态系统。少数评论还对 Astral 早先反对出售的立场表示怀疑,而另一些人则认为收购很常见。总体而言,该讨论串将对 Ty 成熟度的赞赏与更广泛的 Python 工具竞争和企业所有权讨论结合在一起。
相关文章

原文

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.

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.)

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.

ty’s PyPI downloads grew 29x between October 2025 and October 2026

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.

from typing import TypedDict

class Runner(TypedDict):

def podium(runners: list[Runner]) -> list[Runner]:

[*runners, {"name": "Ada", "seconds": 53.2}],

key=lambda runner: runner["second"],

Runner defines a field named seconds.

$ ty check podium.py

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]).

from collections.abc import Callable, Iterable, Sized

*predicates: Callable[[T], bool],

) -> Callable[[T], bool]:

return lambda x: all(p(x) for p in predicates)

def large_enough(batch: Sized) -> bool:

def all_positive(batch: Iterable[int]) -> bool:

return all(n > 0 for n in batch)

valid_batch = satisfies_all(large_enough, all_positive)

valid_batch(iter([1, 2, 3]))

The first predicate needs a value with a length.

$ ty check batches.py

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.

from pathlib import Path

from pydantic import BaseModel, Field

class Options(BaseModel):

simulate: bool = Field(

Options(output="./exports", dry_run=True)

Options(output="./exports", dry_run="true")

Options(output="./exports", simulate=True)

The constructor takes dry_run for this field.

$ ty check options.py

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.

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.

def decode(line: str):

record = logging.makeLogRecord(json.loads(line))

if not hasattr(record, "id"):

raise ValueError("Missing record id")

def show(line: str) -> None:

print(record.id, record.getMessage())

By default, ty treats the result of decode as Unknown.

$ ty check logs.py

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.

from dataclasses import dataclass

def average(self) -> float | None:

return sum(self.scores) / len(self.scores)

The check is meant to handle a quiz with no scores.

$ ty check quiz.py

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.

class Span(typing.NamedTuple):

def midpoint(self) -> int:

return typing.cast(int, self.start + self.end) // 2

Adding two integers already produces an int.

$ ty check span.py

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.

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.

def invoice_total(cents: int) -> int:

The function promises an integer and returns a string.

Saved in ty-baseline.json
No saved diagnostics

Reported by ty check
Line 2Expected int, returned str.

The baseline saves individual diagnostics. A new error in the same file still fails the check.

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 powers completions, code navigation, and diagnostics in your editor.

With the 1.0 release, this integration is available in preview and can now be enabled directly in your ty configuration with project-manager.script = "uv".

Finally, we’ve made ty stricter in some places and more permissive in others.

For example, ty now infers more precise types for containers and attributes without annotations, enabling it to catch errors even in lightly typed code.

def __init__(self) -> None:

policy.attempts = "three"

ty infers that attempts is an int.

$ ty check retries.py

ty infers attempts as int from the assignment in __init__ and flags the string assigned later.

We've also relaxed some of the rules for narrowing types after checks like isinstance, so common Python patterns need fewer casts or annotations.

In the example below, the parameter is annotated as Term | list[Term]. After isinstance(terms, list), we’d usually expect each item to be a Term. But a subclass of Term could also inherit from list[str], so the list could contain strings. ty now accepts term.text by default and flags the access when strict generic narrowing is enabled.

from dataclasses import dataclass

def render(terms: Term | list[Term]) -> str:

if isinstance(terms, list):

parts = [term.text for term in terms]

return " + ".join(parts)

The parameter annotation says that callers can pass a Term or a list of terms.

$ ty check terms.py

Strict generic narrowing still accounts for a Term subclass whose list contains items of another type.

These changes were informed by iterating with users and reviewing real projects in the ecosystem, balancing precision and usefulness with soundness. For users who want to prioritize soundness, ty offers opt-in settings like strict generic narrowing that often go beyond what other type checkers support.

Similarly, ty supports many of the type-enforcement rules popular in mypy’s strict mode, sometimes going further. For example, ty can warn when a function returns Any, including partially-Any cases that mypy’s warn-return-any misses:

def usernames(db: sqlite3.Connection) -> list[str]:

cursor = db.execute("SELECT username FROM users")

return cursor.fetchall()

usernames(db) → [('alice',), ('bob',)]

$ ty check --warn unsound-return users.py

SQLite returns a tuple for each row, even when the query selects one column. Mypy 2.4.1 accepts this function under --strict. With unsound-return enabled, ty flags the list[Any] returned by fetchall().

ty is the most technically ambitious project I have ever worked on. Our goal was to build something genuinely new: an architecture designed around fine-grained incrementality, a novel application of gradual and set-theoretic typing to Python, and a foundation for entirely new kinds of developer tools. I feel immense pride in the core team as we ship 1.0 (Alex, Andrew, Aria, Carl, David, Dhruv, Doug, Ibraheem, Jack, Lérè, Micha, and Shunsuke).

As in the Beta release, our immediate priority from here is supporting users as they adopt ty.

Now that we’ve built the core of our type checker, though, we can start exploring its broader applications: type-aware linting, dead-code elimination, unused dependency analysis, type-aware test selection, and more.

We want to make Python the most productive version of itself. And with ty, we can power an entirely new set of tools and capabilities for the language based on the most sophisticated Python type engine in the world.

Just as with Ruff and uv, our commitment from here is that ty will get significantly better every week by working closely with our users. Thank you for building with us.

联系我们 contact @ memedata.com