Commit Graph
51 Commits
Author SHA1 Message Date
Charlie Marsh d67aa96e6a [ty] Skip overload prefix checks for literal parameters (#31043)
## Summary

When the service name is `Any`, we check whether some prefix of the
overloads accepts every possible value. A prefix that only accepts
literal service names can never cover `object()`. We already use that
observation to skip prefix checks for some parameter types. We now
recognize literal types here too, including unions where every member
excludes `object()`.

Checking `boto3auth` with `boto3-stubs` was 7.7% faster on a single
worker (112 ms to 104 ms, faster in 17 of 18 paired runs). In
`boto3-stubs` 1.44.3, all 435 overloads of `Session.client` take a
literal service name.
2026-11-29 07:50:16 -05:00
Charlie Marsh 3c27fd264e [ty] Skip overload coverage checks when a parameter rules out object (#30866)
## Summary

Given overloads for `str`, `bytes` and `object`, a call with `Any` must
keep the last overload. The first two can’t handle every value the
argument could take. Today we build successively larger unions of
parameter types to find that out.

We now skip those unions when the earlier overloads all see the same
arguments and none can accept `object()` in one of the argument
positions. We still check protocols such as `Hashable`, which `object()`
satisfies.

<!-- ty-pinned-project-instructions:start -->

Across 28 projects, the mean change in instructions was −0.33% and the
median was −0.03%.

We compared cold checks against [main at
d83eb73b](https://github.com/astral-sh/ruff/commit/d83eb73b279c28ff94a6b8fbc30690f816221ba5).
These tables measure [the PR revision before the
rebase](https://github.com/astral-sh/ruff/commit/9abf0eac525d9d0e75dfaaec8b0d1f516f972504)
applied to that commit. They predate #30480. Any figures above are from
earlier runs.

Output varied across runs on Django.

In parallel Django checks, both builds alternated between `Divergent`
and `Unknown` in two messages in `django/db/models/sql/query.py`. The
single-worker outputs matched byte for byte.

<details>
<summary>Instruction counts by project</summary>

Both builds use the linked main commit, with this PR applied to the
second. Counts are medians of four single-worker Cachegrind runs on
Linux (x86-64). Change is the median of four paired percentages. We
marked a result inconclusive when the pairs disagreed in direction or
the change was within the variation between runs of either build.

| Project | [Base
instructions](https://github.com/astral-sh/ruff/commit/d83eb73b279c28ff94a6b8fbc30690f816221ba5)
| [PR
instructions](https://github.com/astral-sh/ruff/commit/9abf0eac525d9d0e75dfaaec8b0d1f516f972504)
| Change | Paired range |
| --- | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
(inconclusive) | 2,758,153,008 | 2,758,444,002.5 | +0.01% | 0.00% to
+0.02% |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
| 6,726,865,693.5 | 6,726,164,026.5 | -0.01% | -0.01% to -0.01% |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| 137,592,074,915.5 | 137,575,342,700 | -0.01% | -0.01% to -0.01% |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
| 1,517,915,046.5 | 1,517,981,239 | 0.00% | 0.00% to +0.01% |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
(inconclusive) | 1,636,014,161.5 | 1,635,842,686 | -0.01% | -0.02% to
-0.01% |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
| 23,926,649,784 | 23,818,594,135.5 | -0.45% | -0.47% to -0.44% |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
(inconclusive) | 2,642,975,975 | 2,642,855,070.5 | 0.00% | -0.01% to
+0.01% |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
(inconclusive) | 4,463,579,601.5 | 4,463,970,686 | +0.01% | 0.00% to
+0.02% |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| 81,969,444,263.5 | 81,930,530,974.5 | -0.05% | -0.05% to -0.03% |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
(inconclusive) | 1,422,732,971 | 1,422,797,374 | 0.00% | 0.00% to +0.01%
|
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
| 8,078,924,448.5 | 8,075,550,521.5 | -0.04% | -0.04% to -0.03% |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
| 2,631,714,127 | 2,630,788,692 | -0.03% | -0.04% to -0.02% |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
| 17,470,521,656.5 | 17,467,751,824.5 | -0.02% | -0.02% to -0.01% |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
(inconclusive) | 2,376,889,580 | 2,376,979,894 | 0.00% | -0.02% to
+0.01% |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
| 11,783,614,433 | 11,774,026,797 | -0.08% | -0.08% to -0.08% |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
| 37,804,903,029.5 | 37,783,848,979 | -0.05% | -0.06% to -0.05% |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
| 13,779,015,123 | 13,777,943,794 | -0.01% | -0.01% to -0.01% |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| 7,647,277,448.5 | 7,644,383,849 | -0.04% | -0.04% to -0.03% |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
| 3,547,307,758.5 | 3,546,933,665 | -0.01% | -0.02% to -0.01% |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
| 12,336,503,045.5 | 12,324,745,465.5 | -0.10% | -0.10% to -0.09% |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
| 2,619,383,539.5 | 2,618,005,601 | -0.06% | -0.06% to -0.04% |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
| 4,179,119,373 | 4,177,335,482 | -0.04% | -0.05% to -0.04% |
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
| 29,057,929,398 | 28,532,824,032.5 | -1.81% | -1.81% to -1.80% |
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
| 13,340,761,860 | 13,178,800,810.5 | -1.21% | -1.22% to -1.21% |
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
| 8,628,016,213 | 8,624,505,013 | -0.04% | -0.04% to -0.04% |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
| 46,556,548,945.5 | 44,146,394,410 | -5.18% | -5.18% to -5.17% |
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
| 7,817,817,379 | 7,816,327,732 | -0.02% | -0.02% to -0.02% |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
| 85,109,723,794.5 | 85,011,484,965 | -0.12% | -0.12% to -0.11% |

</details>

<details>
<summary>Memory by project</summary>

Peak RSS is the median paired change in MiB. We ran 16 pairs with
default parallelism and four with one worker. The last column estimates
retained query storage from two separate single-worker pairs. It
excludes some allocations.

| Project | Peak RSS (MiB) | Pairs with higher RSS | Peak RSS, one
worker (MiB) | Estimated query storage (MiB) |
| --- | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
| +0.34 (+0.30%) | 9/16 | +0.25 | 0.00 (0.00%) |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
| +0.79 (+0.42%) | 11/16 | +0.23 | −0.01 (−0.01%) |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| −1.23 (−0.04%) | 6/16 | −0.09 | −0.21 (−0.01%) |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
| −0.17 (−0.23%) | 7/16 | +0.18 | 0.00 (0.00%) |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
| −0.09 (−0.10%) | 7/16 | +0.28 | −0.01 (−0.02%) |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
| −1.76 (−0.33%) | 7/16 | −1.58 | −1.31 (−0.29%) |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
| −0.27 (−0.20%) | 7/16 | +0.06 | 0.00 (0.00%) |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
| −0.50 (−0.26%) | 5/16 | +0.07 | 0.00 (0.00%) |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| +0.22 (+0.02%) | 8/16 | −0.36 | −0.31 (−0.02%) |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
| −0.13 (−0.15%) | 6/16 | −0.01 | 0.00 (0.00%) |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
| −0.54 (−0.23%) | 7/16 | +0.02 | −0.01 (−0.01%) |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
| −0.39 (−0.31%) | 7/16 | −0.04 | −0.01 (−0.01%) |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
| 0.00 (0.00%) | 8/16 | +0.02 | −0.07 (−0.02%) |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
| −0.31 (−0.29%) | 6/16 | +0.13 | 0.00 (0.00%) |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
| +0.14 (+0.05%) | 10/16 | −0.07 | −0.17 (−0.07%) |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
| −2.89 (−0.45%) | 3/16 | +0.02 | −0.26 (−0.05%) |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
| +0.43 (+0.14%) | 11/16 | −0.17 | 0.00 (0.00%) |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| −0.34 (−0.16%) | 7/16 | +0.06 | −0.02 (−0.01%) |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
| −0.18 (−0.15%) | 5/16 | −0.10 | 0.00 (0.00%) |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
| +0.29 (+0.11%) | 10/16 | −0.18 | −0.24 (−0.11%) |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
| +0.30 (+0.28%) | 10/16 | +0.05 | −0.03 (−0.04%) |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
| −0.28 (−0.20%) | 6/16 | +0.41 | −0.03 (−0.03%) |
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
| −6.84 (−1.19%) | 0/16 | −6.34 | −5.96 (−1.23%) |
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
| −1.55 (−0.57%) | 0/16 | −1.43 | −1.62 (−0.77%) |
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
| +0.21 (+0.16%) | 9/16 | −0.30 | −0.01 (−0.01%) |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
| −15.93 (−2.70%) | 0/16 | −15.83 | −18.67 (−3.47%) |
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
| −0.22 (−0.10%) | 7/16 | +0.20 | −0.03 (−0.02%) |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
| +1.66 (+0.11%) | 9/16 | −1.59 | −1.21 (−0.09%) |

</details>

<!-- ty-pinned-project-instructions:end -->
2026-11-25 08:56:39 -05:00
Charlie Marsh ab37a8e980 [ty] Reuse expression inference across mismatched string literals (#30642)
## Summary

At `boto3.client("s3")`, ty infers `"s3"` against 440 service-specific
`Literal` annotations in `types-boto3`. Expectations like
`Literal["ec2"]` and `Literal["iam"]` give `"s3"` the same type it would
have without an annotation. Each expectation currently gets its own
entry in the expression cache.

We now share the default entry across those mismatches. The matching
`Literal["s3"]` needs its own entry because it suppresses promotion to
`str`. We also use individual entries for files open in the editor,
where completions need every expected service name.

A cold check of Moto’s 39 S3 test files with `types-boto3` 1.44.7 used
13.39–13.49% fewer instructions in two whole-process Cachegrind
comparisons, one in each order. Consecutive runs of the baseline
differed by 0.014%. [Moto S3
tests](https://github.com/getmoto/moto/tree/ecc384b3e75ab471572d0d8d61c53cfd951c0fbc/tests/test_s3)

The measurements above predate the rebase onto `7be385f2`.

<!-- ty-pinned-project-instructions:start -->

Across 28 projects, the mean change in instructions was −0.02% and the
median was −0.02%.

<details>
<summary>Instruction counts by project</summary>

| Project | [Base
instructions](https://github.com/astral-sh/ruff/commit/7be385f21d0848e58668b75cd90d0927637c84b6)
| [PR
instructions](https://github.com/astral-sh/ruff/commit/bee9c40e386a972c10f4e68361e71fbafeb6fc75)
| Change | Paired range |
| --- | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
(inconclusive) | 3,097,484,537 | 3,096,387,080.5 | -0.04% | -0.11% to
+0.04% |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
| 7,953,058,761 | 7,915,346,658.5 | -0.47% | -0.69% to -0.26% |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| 153,016,287,768.5 | 152,969,059,437 | -0.03% | -0.03% to -0.03% |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
(inconclusive) | 1,801,232,283.5 | 1,801,672,422 | +0.02% | -0.09% to
+0.14% |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
(inconclusive) | 1,888,201,411.5 | 1,889,011,497 | +0.04% | +0.03% to
+0.06% |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
(inconclusive) | 27,349,375,688.5 | 27,321,861,731.5 | -0.10% | -0.14%
to -0.06% |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
(inconclusive) | 2,861,383,850.5 | 2,865,117,386 | +0.13% | -0.01% to
+0.27% |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
(inconclusive) | 4,849,740,423.5 | 4,848,572,059 | -0.02% | -0.06% to
+0.01% |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| 92,722,950,044 | 92,864,483,085.5 | +0.15% | +0.10% to +0.20% |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
(inconclusive) | 1,642,218,348 | 1,644,063,625 | +0.11% | +0.08% to
+0.15% |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
(inconclusive) | 8,087,192,937 | 8,080,366,991.5 | -0.08% | -0.13% to
-0.03% |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
| 2,934,835,234.5 | 2,931,876,648.5 | -0.10% | -0.16% to -0.04% |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
(inconclusive) | 20,589,830,741.5 | 20,629,980,241 | +0.19% | +0.10% to
+0.29% |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
(inconclusive) | 2,651,618,004 | 2,653,693,495.5 | +0.08% | +0.05% to
+0.11% |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
(inconclusive) | 13,360,445,031 | 13,346,030,322 | -0.11% | -0.13% to
-0.09% |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
(inconclusive) | 44,306,075,330.5 | 44,315,296,364.5 | +0.02% | -0.01%
to +0.05% |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
(inconclusive) | 15,304,702,523.5 | 15,289,943,139 | -0.10% | -0.22% to
+0.02% |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| 8,545,640,654.5 | 8,535,058,180 | -0.12% | -0.19% to -0.05% |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
(inconclusive) | 4,044,918,352.5 | 4,044,167,135 | -0.02% | -0.03% to
-0.01% |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
| 13,973,532,171.5 | 13,960,868,754 | -0.09% | -0.10% to -0.08% |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
(inconclusive) | 2,918,698,628.5 | 2,919,037,553 | +0.01% | -0.01% to
+0.03% |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
(inconclusive) | 4,630,040,906 | 4,631,522,521.5 | +0.03% | +0.03% to
+0.03% |
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
(inconclusive) | 32,381,970,898.5 | 32,385,282,502.5 | +0.01% | -0.02%
to +0.04% |
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
(inconclusive) | 15,085,979,468 | 15,091,542,500.5 | +0.04% | +0.03% to
+0.04% |
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
| 12,913,530,517.5 | 12,893,782,668 | -0.15% | -0.18% to -0.13% |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
(inconclusive) | 57,159,831,395.5 | 57,156,621,270.5 | -0.01% | -0.08%
to +0.07% |
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
(inconclusive) | 8,665,019,210.5 | 8,672,156,903.5 | +0.08% | +0.08% to
+0.09% |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
(inconclusive) | 95,902,512,851 | 95,838,956,312.5 | -0.07% | -0.10% to
-0.03% |

</details>

<!-- ty-pinned-project-instructions:end -->
2026-11-22 12:44:40 -05:00
Carl Meyer 3e94fa78fd [ty] Preserve argument inference for unannotated overload parameters (#30549)
ty could infer `Unknown` for a call when one overload left a parameter
unannotated and another supplied a type for it. In this example,
`first()` has no arguments to infer `T` from, so its return type
defaults to `int` unless the caller supplies an expected type.

```python
from typing import overload, reveal_type
from typing_extensions import Never, TypeVar

T = TypeVar("T", default=int)

def first(*values: T) -> T:
    return values[0]

@overload
def choose(value, index: int) -> int: ...
@overload
def choose(value: Never, index: object) -> object: ...
def choose(value, index):
    return index

reveal_type(choose(first(), 1))  # previously Unknown, now int
```

Both overloads initially match. The first gives `first()` no expected
type, so it infers `int`. The second infers `Never` for the same
expression. Previously, ty reused `Never` while checking the first
overload and treated the call as ambiguous. It now uses the argument
type inferred for each overload, so the first overload wins.

## Test plan

Checked the original example with a nested `create()` whose return type
is a type variable bounded by `int`. ty reveals `int` for
`choose(create(), 1)`, including when `create()` is replaced by
`next(iter([]))`.
2026-11-18 20:32:53 -08:00
Charlie Marsh 0fc4348401 [ty] Defer overloads with incompatible string literals (#30249)
## Summary

An argument of type `Literal["text"]` cannot satisfy a parameter
annotated as `Literal["number"]`. Once ty has matched a call's arguments
to parameters, it can check the other overloads first. If none succeeds,
ty checks the deferred overloads too, so a failed call retains its usual
diagnostics.

<!-- ty-pinned-project-instructions:start -->

| Project | Base instructions | PR instructions | Change | Paired range
|
|---|---:|---:|---:|---:|
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
| 3,967,724,712 | 3,962,839,557 | -0.08% | -0.37% to +0.04% |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
| 10,665,599,316 | 10,049,262,782 | -5.79% | -6.07% to -5.38% |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
| 17,855,653,429 | 17,767,335,238 | -0.49% | -1.73% to +1.53% |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
| 4,150,920,734 | 3,841,793,547 | -7.45% | -7.67% to -7.17% |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| 195,029,192,516 | 195,643,374,838 | -0.02% | -0.36% to +0.55% |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
| 2,161,065,020 | 2,166,180,156 | +0.16% | -0.37% to +0.76% |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
| 2,265,149,258 | 2,257,494,222 | -0.29% | -0.95% to +0.49% |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
| 2,438,147,328 | 2,437,288,335 | -0.14% | -0.89% to +0.80% |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
| 11,404,709,586 | 11,349,348,262 | -0.37% | -0.87% to +0.38% |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
| 20,561,724,740 | 20,504,037,318 | -0.35% | -1.61% to +0.31% |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
| 36,373,344,042 | 36,302,070,814 | -0.25% | -0.66% to -0.07% |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
| 4,279,723,883 | 4,280,205,896 | +0.05% | -0.64% to +0.48% |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
| 6,415,376,794 | 6,415,379,580 | -0.20% | -0.97% to +0.50% |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| 11,008,266,198 | 10,962,731,598 | -0.50% | -1.15% to +0.36% |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| 114,432,476,753 | 114,439,142,336 | +0.03% | -0.26% to +0.18% |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
| 3,416,195,804 | 3,399,412,370 | -0.53% | -0.80% to -0.08% |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
| 25,734,388,316 | 25,666,253,494 | -0.37% | -0.74% to +0.20% |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
| 55,479,229,681 | 55,481,055,920 | 0.00% | -0.44% to +0.36% |

<!-- ty-table-revisions base=25c2129f4ef1f0048b36c329502f57ee64ba6f53
head=513c73ba566da43dc9429688268e40ea9e163673 default-pairs=8
single-worker-pairs=4 -->

<!-- ty-pinned-project-instructions:end -->
2026-11-12 13:05:58 -05:00
Alex WaygoodandDavid Peter d65c056994 [ty] Split invalid-key into three TypedDict diagnostic rules (#29955)
## Summary

Given a `Movie` TypedDict with a `title` field, ty currently reports
`invalid-key` for three cases. This PR gives each its own rule.

| Example | Rule |
| --- | --- |
| `movie["titel"]` reads a misspelled key | `invalid-typed-dict-key` |
| `movie[key]` reads a key whose type is `str` and whose value is
unknown | `non-literal-typed-dict-key` |
| `Movie(title="Alien", titel="Alien")` supplies an unknown key during
construction | `unknown-typed-dict-constructor-key` |

Both subscript rules apply to reads and assignments. An invalid
non-string key such as `movie[0]` reports `invalid-typed-dict-key`. The
constructor rule reports the extra `titel` key in `movie: Movie =
{"title": "Alien", "titel": "Alien"}`. For a closed TypedDict, it flags
`{key: value}` when `key` has type `str` and might introduce an extra
item.

Projects migrating to ty lose typo detection if they disable
`invalid-key` to allow dynamic TypedDict lookups. In mypy, disabling
`literal-required` allows `movie[key]` while `movie["titel"]` still
produces a `typeddict-item` error. Pyright allows the dynamic lookup by
default and also flags the typo. To keep that behavior in ty, set
`non-literal-typed-dict-key` to `ignore` and leave
`invalid-typed-dict-key` enabled.

All three rules default to `error`. With the alias handling from #29960,
`invalid-key` maps to `invalid-typed-dict-key` in configuration, inline
ignores, and existing baselines. Previously baselined diagnostics can
therefore reappear under either of the other two rule names. To preserve
a custom severity across the split, set all three rules to the same
level. For inline ignores, use the rule or rules reported on that line.

---------

Co-authored-by: David Peter <mail@david-peter.de>
2026-11-06 15:34:17 +00:00
Alex Waygood 0471c14d1f [ty] Rename unresolved-import to import-not-found (#29960)
## Summary

ty currently reports `unresolved-import` for both a missing module and a
missing member in a `from` import. But the word "unresolved" is heavily
overloaded in Python, and has been reported by users as being confusing
(see https://github.com/astral-sh/ty/issues/2471). This PR renames the
rule to `import-not-found`, which describes the lookup failure in either
case.

Configuration, command-line flags, and ignore comments accept either
spelling. If several flags set this rule’s severity using different
spellings, the last flag wins. Existing baseline entries still match,
and rewriting a baseline uses the new name. Links to the old rule
heading still work.
2026-11-03 19:53:26 +00:00
Carl Meyer ef02d60435 [ty] Preserve shared structure in ambiguous overload return types (#29342)
When gradual arguments leave multiple overloads applicable, ty can lose
useful information by collapsing the entire return type to `Unknown`.
For example, receiver overloads returning `Series[Timestamp]` and
`Series[Timedelta]` produce `Unknown` for a `Series[Any]` receiver.

Preserve shared return-type structure and replace only differing parts
with the existing overload-ambiguity marker. The example now produces
`Series[Unknown]`, retaining member checking on the returned container.
This applies recursively to matching generic classes, tuple shapes, and
`type[...]`, including through recursive aliases. Other structural
differences fall back to `Unknown`.

Compare all remaining return types together so equivalent types with
different representations cannot make the result depend on overload
declaration order. Overload applicability and argument expansion
continue to use the existing selection rules.

Closes astral-sh/ty#4055.

## Ecosystem report

Verified head
[`d32af57e`](https://github.com/astral-sh/ruff/commit/d32af57e7774744bba2e5b425b186106f4d4b1b1)
against the [fresh ecosystem
run](https://github.com/astral-sh/ruff/actions/runs/38585724938). Its
441 retained diagnostic changes match the previous analysis, apart from
an upstream Scrapy line shift. The documented pre-existing checker and
stub limitations remain unchanged; no new ecosystem finding was
introduced by these comment and mdtest updates. Full analysis and
reproduction provenance: [part
1](https://github.com/astral-sh/ruff/pull/29342#issuecomment-6158340152)
and [part
2](https://github.com/astral-sh/ruff/pull/29342#issuecomment-6158339795).
2026-10-14 09:06:54 -07:00
AmirshokhandCharlie Marsh e721ecefb1 [ty] Leave room for later positional arguments when unpacking a variable-length argument (#29293)
## Summary

This PR fixes a bug where unpacking something like `*args` would eat up
all the remaining positional parameters. Because of this, if you passed
another explicit argument *after* the unpack (like `f(*args, x)`), the
type checker thought there was no space left for `x`. This caused false
positive `too-many-positional-arguments` or `invalid-argument-type`
errors.

To fix this, we updated the logic in `bind.rs`. Now, if a function
doesn't have a variadic parameter, we count how many explicit positional
arguments come after the unpack and reserve room for them so everything
fits properly.

Part of: astral-sh/ty#3649.

---------

Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
2026-10-12 20:49:43 -04:00
Zsolt DollensteinandTamir Duberstein da9e37289d [ty] Preserve literal unpacking during call analysis (#28821)
Calls such as `pair(*[1, "two"])` and `pair(**{"x": 1, "y": "two"})`
lose their exact argument count and individual types during call
analysis.

Retain the contents of immediate list and tuple literals, and
dictionaries with explicit string keys. Use that information for
argument matching, overload selection, `TypeVarTuple` inference, and
signature help. Preserve it through `ParamSpec` forwarding, including
dictionaries that also supply wrapper parameters.

Adapted from [Tamir Duberstein’s original
change](https://github.com/tamird/ruff/commit/26e5603efa8e650108f332ac4ee84562c265c38f).

Related to
[astral-sh/ty#3792](https://github.com/astral-sh/ty/issues/3792), but
doesn't fully fix it. The current PR only works for literals constructed
directly in the call expression, but for example:

```python
params = {"sep": "foo", "end": "baz"}
print(*range(5), **params)
```
isn't recognized by this implementation (as the type of `params` is an
open `dict[str, str]`).

---------

Co-authored-by: Tamir Duberstein <tamird@gmail.com>
2026-10-06 14:19:14 +01:00
Zsolt Dollenstein 94c7afbcbb [ty] Refactor call argument representation (#29112)
Call matching handles starred arguments in several places, with each
consumer interpreting the inferred source type separately. This makes it
difficult to carry more precise unpacked values through call analysis.

Represent positional, keyword, and unpacked arguments as distinct
`CallArgument` variants. Move sequence and keyword unpacking into the
argument types, and share those operations across matching, overload
expansion, and partial application. Keep one entry per source argument
so diagnostics and signature help can refer to the original call.

This is a behavior-preserving refactor that prepares for literal
unpacking. The overload regression test covers a variable-length
argument matched to different arities before a keyword argument.
2026-10-06 14:19:14 +01:00
Charlie Marsh 1df6db3e46 [ty] Preserve tuple subclass identity during type expansion (#29090)
## Summary

We now recognize exhaustive class patterns over tuple subclasses,
including `NamedTuple`. For example, this function no longer produces an
`invalid-return-type` error:

```python
from typing import NamedTuple

class Point(NamedTuple):
    x: bool

def handle(value: Point) -> int:
    match value:
        case Point():
            return 42
```

Tuple expansion now intersects each expanded tuple with the original
subclass, preserving its class identity during reachability analysis and
overload resolution.

Closes https://github.com/astral-sh/ty/issues/4659.
2026-10-03 15:08:14 -04:00
Dhruv Manilawala 77caa81e7a [ty] Retain individual overload argument expansion outcomes (#28825)
## Summary

Retain the selected overloads, inferred bindings, and return type for
each expanded argument list before merging results. This preserves
distinct specializations of the same generic overload and prevents
ambiguity in one expansion from affecting a later expansion's return
type.

## Test Plan

Add coverage for independent generic specializations, failed union
members, and an ambiguous expansion followed by an unambiguous
expansion, with generic examples in both legacy and PEP 695 syntax.

<!-- codex-thread: 01a0a543-bbbd-7483-82bd-f1c83509c973 -->
2026-10-01 13:04:38 +05:30
Shunsuke ShibayamaandCarl Meyer 160ffbf2cf [ty] Introduce Recursive types and fully support recursive implicit type aliases (#28425)
## Summary

Closes https://github.com/astral-sh/ty/issues/1738
(While this PR also resolves the error in the code provided in
https://github.com/astral-sh/ty/issues/1846, I consider the broader
issue under discussion to still be unresolved)

To fully support implicit type aliases, this PR introduces `Recursive`
types. These represent *structural recursive types*. In other words,
they are anonymous recursive types implicitly constructed through type
inference, rather than a nominally defined recursive type like PEP 695
recursive type aliases.

This is what was being discussed in
https://github.com/astral-sh/ruff/pull/24252#issuecomment-4172655350. We
are not introducing recursive types solely for implicit type aliases;
this is the first step toward completely replacing the current
`Divergent`-based approximate recursive type inference with a full
implementation.

Initially, I planned to completely remove the `Divergent` type alongside
the introduction of `Recursive` types, but because the scope of the
impact was far too large, I decided to replace it incrementally. Both
will coexist until the replacement is complete, but eventually,
everything should be replaced by `Recursive` types.

Following this PR, I plan to use the newly introduced `Recursive` types
to replace various forms of recursive type inference.

## Design

Currently, we approximate and treat recursive type structures generated
by recursive type inference as gradual types containing `Divergent`. For
example, a subscript on `x: Divergent` results in `x[n]: Divergent`.
Consequently, we get:

```
x: list[Divergent]
x[n]: Divergent
x[n][n]: Divergent
```

As a result, the type after subscripting loses the information that `x`
was a recursive list type. We solve this problem by introducing
recursive types.

`RecursiveType` is a binder for a body type that contains a recursive
variable. In other words, it roughly has the following structure:

```rust
struct RecursiveType<'db> {
    id: salsa::Id,
	body: Type<'db>,
	arguments: Option<Specialization<'db>>,
}

struct RecursiveVar<'db> {
    id: salsa::Id,
    arguments: Option<Specialization<'db>>,
}

enum Type<'db> {
    Recursive(RecursiveType<'db>),
    RecursiveVar(RecursiveVar<'db>),
    ...
}
```

For example, for the following implicit type alias:

```python
Tree = tuple[T, "Tree[list[T]] | None"]
# = μF. λT. tuple[T, F[list[T]] | None]
```

the constructed `RecursiveType` looks like this:

```rust
RecursiveType {
    id,
    body: tuple[T, RecursiveVar { id, arguments: [list[T]] } | None],
    arguments: [T]
}
```

Unlike `Divergent`, the recursive variable `RecursiveVar` has no type
properties on its own. Attempting to access this variable immediately
unfolds the recursive type, so questioning the typing properties of the
variable itself is meaningless. Therefore, if any type operation on
`RecursiveVar` appears, it should be a bug.

To infer the container subscript `x[1]` for `x: Tree[int]`, first unfold
`x`'s type. Unfolding replaces references to the recursive binder with
the recursive type itself. Writing `B[a := R]` for capture-avoiding
substitution of `R` for `a` in `B`:

```text
unfold(μa. B) = B[a := μa. B]
```

For `Tree[int]`, substitute the constructor for `F`, then apply `T :=
int`:

```text
unfold((μF. λT. tuple[T, F[list[T]] | None])[int])
= tuple[int, (μF. λT. tuple[T, F[list[T]] | None])[list[int]] | None]
(= tuple[int, Tree[list[int]] | None])
```

Tuple subscripting then selects the element at index 1: `x[1]:
Tree[list[int]] | None`.

## Test Plan

mdtest updated

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
2026-09-18 04:01:49 +09:00
Carl Meyer 083ec1e307 [ty] Fix overload argument expansion with unpacked positional arguments (#27744)
## Summary

Fixes astral-sh/ty#4258.

The overload-expansion optimization compared an unpacked iterable
against an individual parameter's type, causing valid calls with `*args`
to be rejected before an unrelated union-typed argument could be
expanded.

- Check each unpacked element against its actual matched parameter
instead of comparing the entire iterable.
- Treat empty unpacking as imposing no positional constraint.
- Preserve existing behavior for unresolved variadic generics and retain
early pruning for incompatible arguments.

## Test plan

Added overload-resolution mdtests covering empty unpacking, fixed-length
and variable-length tuples, lists, invalid unpacked elements,
heterogeneous positional parameters, unpacked tuple annotations,
unresolved variadic generic prefixes, and early pruning of invalid
nonempty unpacking.
2026-08-14 07:04:11 -04:00
Alex Waygood 6ffd512049 [ty] Move Unknown into ty_extensions._internal (#27430) 2026-08-03 13:03:38 +01:00
Ed Page 958efb1ff4 Vendor latest annotate-snippets (#27033)
## Summary

This is a first step towards #20411. After this, we would work to either
upstream changes or adjust things within Ruff.

Performance improvements have already been upstreamed
(https://github.com/rust-lang/annotate-snippets-rs/pull/437,
https://github.com/rust-lang/annotate-snippets-rs/pull/440)

Re-implemented the following from the fork:
- Hidden snippets
(https://github.com/rust-lang/annotate-snippets-rs/issues/448)
- Renderer-level disabling of hyperlinks
- Jupyter cell indices
(https://github.com/rust-lang/annotate-snippets-rs/issues/449)
- Fixable mark
(https://github.com/rust-lang/annotate-snippets-rs/issues/450)
- `lineno_offset` (maybe not needed if #20648 is taken care of)
- anonymized lines affects origin
(https://github.com/rust-lang/annotate-snippets-rs/issues/451)
- cut indicator (maybe not needed if we can switch to unicode renderer)

Additional hacks to minimize behavior change include
- Adjust upstream's hidden severity behavior to match Ruff's
(https://github.com/rust-lang/annotate-snippets-rs/issues/452)
- How newlines are annotated
(https://github.com/rust-lang/annotate-snippets-rs/issues/454)
- To not indent for line numbers when none will be present
(https://github.com/rust-lang/annotate-snippets-rs/issues/453)
- Enabling `simd` by default

All of the above represents work that needs to be resolved to address
#20411.

`lib.name` hack is used to simplify maintenance with the assumption that
we'll continue working towards #20411.

Behavior changes that were included
- Tweak when implicit padding lines are present
- Fix Origin's line/column is now derived from the primary annotation
- Make consistent the rendering of primary/context annotations
- Fix snippets to show up for empty source (but may degrade #24528)
- Fix handling of term width
- Fix rendering of annotations between newline and first character
(granted, maybe the caller is wrong)
- Tweak multiline annotation markers

New or upcoming features annotate-snippets features that we will be able
to leverage by moving this forward
- `AnnotationKind::Visible` to improve the quality of built-in
code-folding if Ruff were to switch to it
- `DecorStyle::Unicode`
- *(upcoming)* No-graphiscs mode for screen readers (may also be useful
for AIs)

Deferred:
- Moving related `Group`s into the same `Report`
- Using `secondary_title` for any `Group` after the first in a `Report`
- Using a `Snippet`, instead of titles, for "virtual code" like
https://github.com/astral-sh/ruff/pull/27033#discussion_r3622727236
- Switching hidden snippets to `Origin`

## Test Plan

Within cpython, I ran
```console
$ hyperfine -i "../../ruff/target-baseline/release/ruff check" "../../ruff/target-update/release/ruff check" -N -m20 --output=null
Benchmark 1: ../../ruff/target-baseline/release/ruff check
  Time (mean ± σ):      27.5 ms ±   1.1 ms    [User: 33.0 ms, System: 108.4 ms]
  Range (min … max):    25.0 ms …  31.7 ms    94 runs

  Warning: Ignoring non-zero exit code.

Benchmark 2: ../../ruff/target-update/release/ruff check
  Time (mean ± σ):      28.1 ms ±   2.0 ms    [User: 33.4 ms, System: 105.7 ms]
  Range (min … max):    24.8 ms …  38.9 ms    102 runs

  Warning: Ignoring non-zero exit code.
  Warning: Statistical outliers were detected. Consider re-running this benchmark on a quiet system without any interferences from other programs. It might help to use t
he '--warmup' or '--prepare' options.

Summary
  ../../ruff/target-baseline/release/ruff check ran
    1.03 ± 0.08 times faster than ../../ruff/target-update/release/ruff check
```

Before:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/2d94dabf-b28d-48c1-b17c-52aac59fd57e"
/>

After:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/b388ada3-e3d7-4ba0-b90b-1330eb81f4be"
/>
2026-07-28 11:57:09 -05:00
Ibraheem Ahmed 29344141c4 [ty] Implement unified generic call inference (#26141)
Generic call inference faces the problem of how to provide unspecialized
parameter types as type context to call arguments. We currently
specialize parameter types based on the annotated type of the call
expression. However, for unannotated calls, we fail to account for
constraints contributed by sibling arguments, for example:

```py
def f[T](x: T, y: list[T]) -> T:
    return x

def _(x: int | str, y: int):
    f(x, [y]) # error[invalid-argument-type]: Expected `list[int | str]`, found `list[int]`
```

Or a more complex example, which pyright is also unable to solve:
```py
def f[T](x: T, y: list[T], z: list[T]) -> T:
    return x

def _(x: int | str, y: int, z: int | str | None):
    f(x, [y], [z]) # error[invalid-argument-type]: Expected `list[int | str | None]`, found `list[int]`
```

We also fail to provide useful type coverage for lambda expressions in
generic signatures:
```py
x = map(lambda x: reveal_type(x) + 2, [1, 2, 3]) # revealed: Unknown
reveal_type(x) # revealed: map[Unknown]
```

This PR extends generic call inference to perform fixpoint iteration,
allowing inferred argument types to contribute type context constraints
to future iterations, until convergence. This allows us solve all the
examples above, as well as handle complex chains of dependencies such as
the following, which no other type checker currently supports:
```py
def chain[A, B, C, D](
    first: Callable[[C], D],
    second: Callable[[B], C],
    third: Callable[[A], B],
    source: list[A],
) -> D:
    return first(second(third(source[0])))

reveal_type(chain(  # revealed: int
    lambda c: reveal_type(c) + 1, # revealed: int
    lambda b: reveal_type(b) + 1, # revealed: int
    lambda a: reveal_type(a) + 1, # revealed: int
    [1, 2, 3],
))
```

Resolves https://github.com/astral-sh/ty/issues/2521, which I split into
a few sub-issues that remain as limitations of the fixpoint scheme. This
also resolves https://github.com/astral-sh/ty/issues/3469.

To avoid the overhead of multi-inference during fixpoint iteration, this
PR extends our local expression caching to support caching entire
inference region results, including diagnostics. This allows results
from speculative inference rounds to be reused during the final round of
fixpoint iteration. As a result, this PR is able to resolve
https://github.com/astral-sh/ty/issues/3597 with relatively minimal
overhead, which accounts for some of the new previously-suppressed
ecosystem diagnostics.

This also removes a significant part of the code added in
https://github.com/astral-sh/ruff/pull/24934, as the `ParamSpec`
re-inference path now naturally falls out of fixpoint iteration. I also
ended up reverting https://github.com/astral-sh/ruff/pull/26252 as part
of this change, as the performance implications seemed negligible, and I
don't think it warrants the extra complexity that it grew into (which
accounts for the small memory usage regression).
2026-07-15 17:48:49 -04:00
David Peter 7b3b6a0b8c [ty] Split ty_extensions into public and internal parts (#26586)
## Summary

Split `ty_extensions` into a public part (`ty_extensions`), and an
internal part (`ty_extensions._internal`). For now, move everything to
`_internal`, except for:

- `static_assert`
- `Unknown`
- `AlwaysTruthy`, `AlwaysFalsy`
- `Intersection`, `Not`
- `Top`, `Bottom`
- `JustFloat`, `JustComplex`
- `NamedTupleLike`
2026-07-07 02:32:21 -07:00
Samuel RigaudandSamuel Rigaud 3f0ea98047 fix typos (#26462)
Another round of typos being fixed 

<img width="300" height="200" alt="image"
src="https://github.com/user-attachments/assets/acdaea05-0d28-4537-94db-9a809d76e00c"
/>

Co-authored-by: Samuel Rigaud <rigaud@gmail.com>
2026-07-01 23:23:21 +01:00
David Peter 63160123cf [ty] Respect return-context inference when filtering overloads (#26454)
## Summary

```py
from typing import Any, overload

@overload
def f[T](value: T) -> T: ...
@overload
def f(value: Any) -> Any: ...
def f(value: Any) -> Any: ...

values: list[int] = reveal_type(f([]))  # Before: Unknown, now: list[int]
```

The expected `list[int]` return type specializes `T` and provides
`list[int]` as context for `[]`. Previously, overload filtering lost
that context, treated the argument as `list[Unknown]`, and considered
the call ambiguous. It now preserves the contextual type and selects the
generic overload.

closes https://github.com/astral-sh/ty/issues/3874

## Test plan

- Regression test
- Verified that it fixes the linked bug
2026-06-29 05:49:34 -07:00
Samuel RigaudandSamuel Rigaud d78b3d5f32 Fix typos (#26443)
FIix even more typos

Co-authored-by: Samuel Rigaud <rigaud@gmail.com>
2026-06-28 23:23:37 +01:00
Charlie MarshandCodex a2a71c59e1 [ty] Add first-class support for enum complements (#24961)
## Summary

Previously, narrowing an enum by excluding one or more members eagerly
expanded the enum into a union of all remaining enum literals. That's
fine for small enums, but can cause large enums to blow up during
repeated equality or membership narrowing. And large enums are not
uncommon...

This PR keeps those narrowed types in a compact form, like `Color &
~Literal[Color.RED]`, instead of immediately expanding them to
`Literal[Color.GREEN, Color.BLUE, ...]`. The type is expanded only when
we need to inspect the remaining enum members individually (like for
overload matching or attribute lookup). The net effect is that we retain
the existing behavior while avoiding a brutal performance penalty for
large enums.

Note that we do vary some behavior by enum size. For example, with more
than 7 elements, we use (as you can see in the ecosystem diff) the
compact representation (`SupportedBlockchain &
~Literal[SupportedBlockchain.ETHEREUM_BEACONCHAIN`).

For the benchmark in the linked issue, `main` doesn't finish within 30s,
but this PR completes in 128ms.

Closes https://github.com/astral-sh/ty/issues/1588.

---------

Co-authored-by: Codex <noreply@openai.com>
2026-05-19 00:49:42 +01:00
Dhruv Manilawala a1ecc346ed Fix overload step 5 filtering for variadic parameter (#24063)
## Summary

fixes: https://github.com/astral-sh/ty/issues/1825

This is fixed by introducing a local struct that captures the
information for the matching argument-parameter. Specifically, for a
variadic parameter, multiple arguments could potentially match a single
parameter, we expand it so that the number of these matches are same
across all the remaining matching overloads during step 5.

Considering the _new_ example from the test case ("Varidic argument with
generic iterable"):
```py
@overload
def f(x: Iterable[T1], /) -> tuple[T1]: ...
@overload
def f(x: Iterable[T1], y: Iterable[T2], /) -> tuple[T1, T2]: ...
@overload
def f(x: Iterable[T1], y: Iterable[T2], z: Iterable[T3], /) -> tuple[T1, T2, T3]: ...
@overload
def f(*args: Iterable[T]) -> tuple[T, ...]: ...

def _(lista: list[A], listb: list[B]):
    reveal_type(f(lista, listb))  # revealed: tuple[A, B]
```

where,
- Step 1 filters out overloads 0 and 2, remaining overloads are 1 and 3
- Step 2 doesn't filter out any overloads but maps the generic type
variables
- Step 3 (no argument type expansion) and 4 (no variadic arguments)
isn't involved here
- Now, ...

For step 5, we create two slots for each overloads. So, even for the
last overload we have two slots which indicates that both argument
matches the single parameter. This way we're able to go through each
overloads and generate the `top_materialized_argument_type` and
`parameter_types` here
(https://github.com/astral-sh/ruff/blob/798aef889d77ca9756354aed4d33434b6009447d/crates/ty_python_semantic/src/types/call/bind.rs#L3126-L3126)
in a way that the length are the same.

## Test Plan

Fix existing test cases and add new test case.
2026-04-21 15:49:29 +00:00
Alex Waygood be5736e240 [ty] Add contextual secondary annotations in more places (#24696) 2026-04-20 21:12:08 +00:00
David Peter 08629b4954 [ty] Migrate more mdtests to inline snapshots (#24687)
## Summary

Migrate another ~20 test suites to inline snapshots (Friday batch).
2026-04-17 11:49:09 +02:00
Charlie MarshandCarl Meyer 1535879415 [ty] Relax union variadic guard to check only parameters beyond minimum length (#23298)
## Summary

The guard condition for per-element union iteration in match_variadic
previously required all remaining positional parameters to be defaulted.
This was overly conservative. We only need parameters beyond the
shortest union element's length to be defaulted, since those positions
are guaranteed to be provided by every union element.

See: https://github.com/astral-sh/ruff/pull/23124/changes#r2806496807.

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
2026-03-25 14:39:02 -07:00
Alex WaygoodandCarl Meyer 09de8efcdf [ty] Reimplement equivalence as mutual redundancy (#23428)
Co-authored-by: Carl Meyer <carl@oddbird.net>
2026-02-25 23:05:55 +00:00
Amethyst Reese 09db380143 Apply ruff formatting to mdtests (#22935)
- Updated the `prek` hook to replace `blacken-docs` with ruff
- Added some formatting directives to preserve obvious intentional
formatting choices
- Made some choice edits to content for better readability with new format
- Formatted md tests and updated snapshots
2026-02-13 08:48:14 -08:00
Charlie Marsh 80a58e23e8 [ty] Limit fixed-length tuple expansion in overload matching (#23190)
## Summary

When resolving overloaded calls, ty expands tuple arguments via
Cartesian product as required by the
[spec](https://typing.python.org/en/latest/spec/overload.html#argument-type-expansion).
This PR adjusts our behavior to match
[pyright](https://github.com/microsoft/pyright/blob/5a325e4874e775436671eed65ad696787a1ef74b/packages/pyright-internal/src/analyzer/typeEvaluator.ts#L570),
which limits to 64 types for a single tuple and 256 across. (As-is, we
only applied a 512 limit _after_ expanding.)

Closes https://github.com/astral-sh/ty/issues/1870.
2026-02-09 19:43:27 -05:00
Bhuminjay Soni b2d57ddaa5 [ty]: consolidate type[] types in a union when displaying them in diagnostics (#22592) 2026-01-15 15:20:58 +00:00
Carl Meyer 87110c2892 [ty] Fix PEP 695 type aliases not expanding in overload resolution (#22589)
Fixes https://github.com/astral-sh/ty/issues/2488

When a type alias is defined using PEP 695's `type` statement syntax
(e.g., `type Array = Eager | Lazy`), overload resolution was failing
because the type alias was not being expanded into its underlying union
type.

This fix updates both `expand_type` and `is_expandable_type` in
`arguments.rs` to handle `Type::TypeAlias` by recursively checking and
expanding the alias's value type.
2026-01-15 06:25:08 +00:00
Dhruv Manilawala c35bf8f441 [ty] Fix overload filtering to prefer more "precise" match (#21859)
## Summary

fixes: https://github.com/astral-sh/ty/issues/1809

I took this chance to add some debug level tracing logs for overload
call evaluation similar to Doug's implementation in `constraints.rs`.

## Test Plan

- Add new mdtests
- Tested it against `sqlalchemy.select` in pyx which results in the
correct overload being matched
2025-12-09 20:29:34 +05:30
Ibraheem Ahmed 3c8fb68765 [ty] dict is not assignable to TypedDict (#21238)
## Summary

A lot of the bidirectional inference work relies on `dict` not being
assignable to `TypedDict`, so I think it makes sense to add this before
fully implementing https://github.com/astral-sh/ty/issues/1387.
2025-11-03 16:57:49 -05:00
Alex Waygood 7064c38e53 [ty] Filter out revealed-type and undefined-reveal diagnostics from mdtest snapshots (#20820) 2025-10-12 18:39:32 +00:00
Alex Waygood f054b8a55e [ty] Improve assignability/subtyping between two protocol types (#20368) 2025-10-08 18:37:30 +00:00
Ibraheem Ahmed 2ce3aba458 [ty] Use annotated parameters as type context (#20635)
## Summary

Use the type annotation of function parameters as bidirectional type
context when inferring the argument expression. For example, the
following example now type-checks:

```py
class TD(TypedDict):
    x: int

def f(_: TD): ...

f({ "x": 1 })
```

Part of https://github.com/astral-sh/ty/issues/168.
2025-10-03 17:14:51 -04:00
Dhruv Manilawala 4e94b22815 [ty] Support single-starred argument for overload call (#20223)
## Summary

closes: https://github.com/astral-sh/ty/issues/247

This PR adds support for variadic arguments to overload call evaluation.

This basically boils down to making sure that the overloads are not
filtered out incorrectly during the step 5 in the overload call
evaluation algorithm. For context, the step 5 tries to filter out the
remaining overloads after finding an overload where the materialization
of argument types are assignable to the parameter types.

The issue with the previous implementation was that it wouldn't unpack
the variadic argument and wouldn't consider the many-to-one (multiple
arguments mapping to a single variadic parameter) correctly. This PR
fixes that.

## Test Plan

Update existing test cases and resolve the TODOs.
2025-10-02 10:41:56 -04:00
Dhruv Manilawala 35ed55ec8c [ty] Filter overloads using variadic parameters (#20547)
## Summary

Closes: https://github.com/astral-sh/ty/issues/551

This PR adds support for step 4 of the overload call evaluation
algorithm which states that:

> If the argument list is compatible with two or more overloads,
determine whether one or more of the overloads has a variadic parameter
(either `*args` or `**kwargs`) that maps to a corresponding argument
that supplies an indeterminate number of positional or keyword
arguments. If so, eliminate overloads that do not have a variadic
parameter.

And, with that, the overload call evaluation algorithm has been
implemented completely end to end as stated in the typing spec.

## Test Plan

Expand the overload call test suite.
2025-09-25 14:58:00 +00:00
Dhruv Manilawala bb9be263c7 [ty] Retry parameter matching for argument type expansion (#20153)
## Summary

This PR addresses an issue for a variadic argument when involved in
argument type expansion of overload call evaluation.

The issue is that the expansion of the variadic argument could result in
argument list of different arity. For example, in `*args: tuple[int] |
tuple[int, str]`, the expansion would lead to the variadic argument
being unpacked into 1 and 2 element respectively. This means that the
parameter matching that was performed initially isn't sufficient and
each expanded argument list would need to redo the parameter matching
again.

This is currently done by redoing the parameter matching directly,
maintaining the state of argument forms (and the conflicting forms), and
updating the `Bindings` values if it changes.

Closes: astral-sh/ty#735

## Test Plan

Update existing mdtest.
2025-09-12 08:40:07 +00:00
Dhruv Manilawala 4ca38b2974 [ty] Unpack variadic argument type in specialization (#20130)
## Summary

This PR fixes various TODOs around overload call when a variadic
argument is used.

The reason this bug existed is because the specialization wouldn't
account for unpacking the type of the variadic argument.

This is fixed by expanding `MatchedArgument` to contain the type of that
argument _only_ when it is a variadic argument. The reason is that
there's a split for when the argument type is inferred -- the
non-variadic arguments are inferred using `infer_argument_types` _after_
parameter matching while the variadic argument type is inferred _during_
the parameter matching. And, the `MatchedArgument` is populated _during_
parameter matching which means the unpacking would need to happen during
parameter matching.

This split seems a bit inconsistent but I don't want to spend a lot of
time on trying to merge them such that all argument type inference
happens in a single place. I might look into it while adding support for
`**kwargs`.

## Test Plan

Update existing tests by resolving the todos.

The ecosystem changes looks correct to me except for the `slice` call
but it seems that it's unrelated to this PR as we infer `slice[Any, Any,
Any]` for a `slice(1, 2, 3)` call on `main` as well
([playground](https://play.ty.dev/9eacce00-c7d5-4dd5-a932-4265cb2bb4f6)).
2025-08-29 04:27:28 +00:00
Alex Waygood ce1dc21e7e [ty] Fix the inferred interface of specialized generic protocols (#19866) 2025-08-27 18:16:15 +01:00
Dhruv Manilawala 376e3ff395 [ty] Limit argument expansion size for overload call evaluation (#20041)
## Summary

This PR limits the argument type expansion size for an overload call
evaluation to 512.

The limit chosen is arbitrary but I've taken the 256 limit from Pyright
into account and bumped it x2 to start with.

Initially, I actually started out by trying to refactor the entire
argument type expansion to be lazy. Currently, expanding a single
argument at any position eagerly creates the combination (argument
lists) and returns that (`Vec<CallArguments>`) but I thought we could
make it lazier by converting the return type of `expand` from
`Iterator<Item = Vec<CallArguments>>` to `Iterator<Item = Iterator<Item
= CallArguments>>` but that's proving to be difficult to implement
mainly because we **need** to maintain the previous expansion to
generate the next expansion which is the main reason to use
`std::iter::successors` in the first place.

Another approach would be to eagerly expand all the argument types and
then use the `combinations` from `itertools` to generate the
combinations but we would need to find the "boundary" between arguments
lists produced from expanding argument at position 1 and position 2
because that's important for the algorithm.

Closes: https://github.com/astral-sh/ty/issues/868

## Test Plan

Add test case to demonstrate the limit along with the diagnostic
snapshot stating that the limit has been reached.
2025-08-25 09:43:04 +00:00
Dhruv Manilawala d43a3d34dd [ty] Avoid unnecessary argument type expansion (#19999)
## Summary

Part of: https://github.com/astral-sh/ty/issues/868

This PR adds a heuristic to avoid argument type expansion if it's going
to eventually lead to no matching overload.

This is done by checking whether the non-expandable argument types are
assignable to the corresponding annotated parameter type. If one of them
is not assignable to all of the remaining overloads, then argument type
expansion isn't going to help.

## Test Plan

Add mdtest that would otherwise take a long time because of the number
of arguments that it would need to expand (30).
2025-08-21 06:13:11 +00:00
Dhruv Manilawala f019cfd15f [ty] Use specialized parameter type for overload filter (#19964)
## Summary

Closes: https://github.com/astral-sh/ty/issues/669

(This turned out to be simpler that I thought :))

## Test Plan

Update existing test cases.

### Ecosystem report

Most of them are basically because ty has now started inferring more
precise types for the return type to an overloaded call and a lot of the
types are defined using type aliases, here's some examples:

<details><summary>Details</summary>
<p>

> attrs (https://github.com/python-attrs/attrs)
> + tests/test_make.py:146:14: error[unresolved-attribute] Type
`Literal[42]` has no attribute `default`
> - Found 555 diagnostics
> + Found 556 diagnostics

This is accurate now that we infer the type as `Literal[42]` instead of
`Unknown` (Pyright infers it as `int`)

> optuna (https://github.com/optuna/optuna)
> + optuna/_gp/search_space.py:181:53: error[invalid-argument-type]
Argument to function `_round_one_normalized_param` is incorrect:
Expected `tuple[int | float, int | float]`, found `tuple[Unknown |
ndarray[Unknown, <class 'float'>], Unknown | ndarray[Unknown, <class
'float'>]]`
> + optuna/_gp/search_space.py:181:83: error[invalid-argument-type]
Argument to function `_round_one_normalized_param` is incorrect:
Expected `int | float`, found `Unknown | ndarray[Unknown, <class
'float'>]`
> + tests/gp_tests/test_search_space.py:109:13:
error[invalid-argument-type] Argument to function
`_unnormalize_one_param` is incorrect: Expected `tuple[int | float, int
| float]`, found `Unknown | ndarray[Unknown, <class 'float'>]`
> + tests/gp_tests/test_search_space.py:110:13:
error[invalid-argument-type] Argument to function
`_unnormalize_one_param` is incorrect: Expected `int | float`, found
`Unknown | ndarray[Unknown, <class 'float'>]`
> - Found 559 diagnostics
> + Found 563 diagnostics

Same as above where ty is now inferring a more precise type like
`Unknown | ndarray[tuple[int, int], <class 'float'>]` instead of just
`Unknown` as before

> jinja (https://github.com/pallets/jinja)
> + src/jinja2/bccache.py:298:39: error[invalid-argument-type] Argument
to bound method `write_bytecode` is incorrect: Expected `IO[bytes]`,
found `_TemporaryFileWrapper[str]`
> - Found 186 diagnostics
> + Found 187 diagnostics

This requires support for type aliases to match the correct overload.

> hydra-zen (https://github.com/mit-ll-responsible-ai/hydra-zen)
> + src/hydra_zen/wrapper/_implementations.py:945:16:
error[invalid-return-type] Return type does not match returned value:
expected `DataClass_ | type[@Todo(type[T] for protocols)] | ListConfig |
DictConfig`, found `@Todo(unsupported type[X] special form) | (((...) ->
Any) & dict[Unknown, Unknown]) | (DataClass_ & dict[Unknown, Unknown]) |
dict[Any, Any] | (ListConfig & dict[Unknown, Unknown]) | (DictConfig &
dict[Unknown, Unknown]) | (((...) -> Any) & list[Unknown]) | (DataClass_
& list[Unknown]) | list[Any] | (ListConfig & list[Unknown]) |
(DictConfig & list[Unknown])`
> + tests/annotations/behaviors.py:60:28: error[call-non-callable]
Object of type `Path` is not callable
> + tests/annotations/behaviors.py:64:21: error[call-non-callable]
Object of type `Path` is not callable
> + tests/annotations/declarations.py:167:17: error[call-non-callable]
Object of type `Path` is not callable
> + tests/annotations/declarations.py:524:17:
error[unresolved-attribute] Type `<class 'int'>` has no attribute
`_target_`
> - Found 561 diagnostics
> + Found 566 diagnostics

Same as above, this requires support for type aliases to match the
correct overload.

> paasta (https://github.com/yelp/paasta)
> + paasta_tools/utils.py:4188:19: warning[redundant-cast] Value is
already of type `list[str]`
> - Found 888 diagnostics
> + Found 889 diagnostics

This is correct.

> colour (https://github.com/colour-science/colour)
> + colour/plotting/diagrams.py:448:13: error[invalid-argument-type]
Argument to bound method `__init__` is incorrect: Expected
`Sequence[@Todo(Support for `typing.TypeAlias`)]`, found
`ndarray[tuple[int, int, int], dtype[Unknown]]`
> + colour/plotting/diagrams.py:462:13: error[invalid-argument-type]
Argument to bound method `__init__` is incorrect: Expected
`Sequence[@Todo(Support for `typing.TypeAlias`)]`, found
`ndarray[tuple[int, int, int], dtype[Unknown]]`
> + colour/plotting/models.py:419:13: error[invalid-argument-type]
Argument to bound method `__init__` is incorrect: Expected
`Sequence[@Todo(Support for `typing.TypeAlias`)]`, found
`ndarray[tuple[int, int, int], dtype[Unknown]]`
> + colour/plotting/temperature.py:230:9: error[invalid-argument-type]
Argument to bound method `__init__` is incorrect: Expected
`Sequence[@Todo(Support for `typing.TypeAlias`)]`, found
`ndarray[tuple[int, int, int], dtype[Unknown]]`
> + colour/plotting/temperature.py:474:13: error[invalid-argument-type]
Argument to bound method `__init__` is incorrect: Expected
`Sequence[@Todo(Support for `typing.TypeAlias`)]`, found
`ndarray[tuple[int, int, int], dtype[Unknown]]`
> + colour/plotting/temperature.py:495:17: error[invalid-argument-type]
Argument to bound method `__init__` is incorrect: Expected
`Sequence[@Todo(Support for `typing.TypeAlias`)]`, found
`ndarray[tuple[int, int, int], dtype[Unknown]]`
> + colour/plotting/temperature.py:513:13: error[invalid-argument-type]
Argument to bound method `text` is incorrect: Expected `int | float`,
found `ndarray[@Todo(Support for `typing.TypeAlias`), dtype[Unknown]]`
> + colour/plotting/temperature.py:514:13: error[invalid-argument-type]
Argument to bound method `text` is incorrect: Expected `int | float`,
found `ndarray[@Todo(Support for `typing.TypeAlias`), dtype[Unknown]]`
> - Found 480 diagnostics
> + Found 488 diagnostics

Most of them are correct except for the last two diagnostics which I'm
not sure
what's happening, it's trying to index into an `np.ndarray` type (which
is
inferred correctly) but I think it might be picking up an incorrect
overload
for the `__getitem__` method.

Scipy's diagnostics also requires support for type alises to pick the
correct overload.

</p>
</details>
2025-08-20 09:39:05 +05:30
Douglas Creager 7673d46b71 [ty] Splat variadic arguments into parameter list (#18996)
This PR updates our call binding logic to handle splatted arguments.

Complicating matters is that we have separated call bind analysis into
two phases: parameter matching and type checking. Parameter matching
looks at the arity of the function signature and call site, and assigns
arguments to parameters. Importantly, we don't yet know the type of each
argument! This is needed so that we can decide whether to infer the type
of each argument as a type form or value form, depending on the
requirements of the parameter that the argument was matched to.

This is an issue when splatting an argument, since we need to know how
many elements the splatted argument contains to know how many positional
parameters to match it against. And to know how many elements the
splatted argument has, we need to know its type.

To get around this, we now make the assumption that splatted arguments
can only be used with value-form parameters. (If you end up splatting an
argument into a type-form parameter, we will silently pass in its
value-form type instead.) That allows us to preemptively infer the
(value-form) type of any splatted argument, so that we have its arity
available during parameter matching. We defer inference of non-splatted
arguments until after parameter matching has finished, as before.

We reuse a lot of the new tuple machinery to make this happen — in
particular resizing the tuple spec representing the number of arguments
passed in with the tuple length representing the number of parameters
the splat was matched with.

This work also shows that we might need to change how we are performing
argument expansion during overload resolution. At the moment, when we
expand parameters, we assume that each argument will still be matched to
the same parameters as before, and only retry the type-checking phase.
With splatted arguments, this is no longer the case, since the inferred
arity of each union element might be different than the arity of the
union as a whole, which can affect how many parameters the splatted
argument is matched to. See the regression test case in
`mdtest/call/function.md` for more details.
2025-07-22 14:33:08 -04:00
David Peter dc66019fbc [ty] Expansion of enums into unions of literals (#19382)
## Summary

Implement expansion of enums into unions of enum literals (and the
reverse operation). For the enum below, this allows us to understand
that `Color = Literal[Color.RED, Color.GREEN, Color.BLUE]`, or that
`Color & ~Literal[Color.RED] = Literal[Color.GREEN, Color.BLUE]`. This
helps in exhaustiveness checking, which is why we see some removed
`assert_never` false positives. And since exhaustiveness checking also
helps with understanding terminal control flow, we also see a few
removed `invalid-return-type` and `possibly-unresolved-reference` false
positives. This PR also adds expansion of enums in overload resolution
and type narrowing constructs.

```py
from enum import Enum
from typing_extensions import Literal, assert_never
from ty_extensions import Intersection, Not, static_assert, is_equivalent_to

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

type Red = Literal[Color.RED]
type Green = Literal[Color.GREEN]
type Blue = Literal[Color.BLUE]

static_assert(is_equivalent_to(Red | Green | Blue, Color))
static_assert(is_equivalent_to(Intersection[Color, Not[Red]], Green | Blue))


def color_name(color: Color) -> str:  # no error here (we detect that this can not implicitly return None)
    if color is Color.RED:
        return "Red"
    elif color is Color.GREEN:
        return "Green"
    elif color is Color.BLUE:
        return "Blue"
    else:
        assert_never(color)  # no error here
```

## Performance

I avoided an initial regression here for large enums, but the
`UnionBuilder` and `IntersectionBuilder` parts can certainly still be
optimized. We might want to use the same technique that we also use for
unions of other literals. I didn't see any problems in our benchmarks so
far, so this is not included yet.

## Test Plan

Many new Markdown tests
2025-07-21 19:37:55 +02:00
David Peter a1edb69ea5 [ty] Enum literal types (#19328)
## Summary

Add a new `Type::EnumLiteral(…)` variant and infer this type for member
accesses on enums.

**Example**: No more `@Todo` types here:
```py
from enum import Enum

class Answer(Enum):
    YES = 1
    NO = 2

    def is_yes(self) -> bool:
        return self == Answer.YES

reveal_type(Answer.YES)  # revealed: Literal[Answer.YES]
reveal_type(Answer.YES == Answer.NO)  # revealed: Literal[False]
reveal_type(Answer.YES.is_yes())  # revealed: bool
```

## Test Plan

* Many new Markdown tests for the new type variant
* Added enum literal types to property tests, ran property tests

## Ecosystem analysis

Summary:

Lots of false positives removed. All of the new diagnostics are
either new true positives (the majority) or known problems. Click for
detailed analysis</summary>

Details:

```diff
AutoSplit (https://github.com/Toufool/AutoSplit)
+ error[call-non-callable] src/capture_method/__init__.py:137:9: Method `__getitem__` of type `bound method CaptureMethodDict.__getitem__(key: Never, /) -> type[CaptureMethodBase]` is not callable on object of type `CaptureMethodDict`
+ error[call-non-callable] src/capture_method/__init__.py:147:9: Method `__getitem__` of type `bound method CaptureMethodDict.__getitem__(key: Never, /) -> type[CaptureMethodBase]` is not callable on object of type `CaptureMethodDict`
+ error[call-non-callable] src/capture_method/__init__.py:148:1: Method `__getitem__` of type `bound method CaptureMethodDict.__getitem__(key: Never, /) -> type[CaptureMethodBase]` is not callable on object of type `CaptureMethodDict`
```

New true positives. That `__getitem__` method is apparently annotated
with `Never` to prevent developers from using it.


```diff
dd-trace-py (https://github.com/DataDog/dd-trace-py)
+ error[invalid-assignment] ddtrace/vendor/psutil/_common.py:29:5: Object of type `None` is not assignable to `Literal[AddressFamily.AF_INET6]`
+ error[invalid-assignment] ddtrace/vendor/psutil/_common.py:33:5: Object of type `None` is not assignable to `Literal[AddressFamily.AF_UNIX]`
```

Arguably true positives:
https://github.com/DataDog/dd-trace-py/blob/e0a772c28bc3897a4b5df73125274999e0f58f30/ddtrace/vendor/psutil/_common.py#L29

```diff
ignite (https://github.com/pytorch/ignite)
+ error[invalid-argument-type] tests/ignite/engine/test_custom_events.py:190:34: Argument to bound method `__call__` is incorrect: Expected `((...) -> Unknown) | None`, found `Literal["123"]`
+ error[invalid-argument-type] tests/ignite/engine/test_custom_events.py:220:37: Argument to function `default_event_filter` is incorrect: Expected `Engine`, found `None`
+ error[invalid-argument-type] tests/ignite/engine/test_custom_events.py:220:43: Argument to function `default_event_filter` is incorrect: Expected `int`, found `None`
+ error[call-non-callable] tests/ignite/engine/test_custom_events.py:561:9: Object of type `CustomEvents` is not callable
+ error[invalid-argument-type] tests/ignite/metrics/test_frequency.py:50:38: Argument to bound method `attach` is incorrect: Expected `Events`, found `CallableEventWithFilter`
```

All true positives. Some of them are inside `pytest.raises(TypeError,
…)` blocks 🙃

```diff
meson (https://github.com/mesonbuild/meson)
+ error[invalid-argument-type] unittests/internaltests.py:243:51: Argument to bound method `__init__` is incorrect: Expected `bool`, found `Literal[MachineChoice.HOST]`
+ error[invalid-argument-type] unittests/internaltests.py:271:51: Argument to bound method `__init__` is incorrect: Expected `bool`, found `Literal[MachineChoice.HOST]`
```

New true positives. Enum literals can not be assigned to `bool`, even if
their value types are `0` and `1`.

```diff
poetry (https://github.com/python-poetry/poetry)
+ error[invalid-assignment] src/poetry/console/exceptions.py:101:5: Object of type `Literal[""]` is not assignable to `InitVar[str]`
```

New false positive, missing support for `InitVar`.

```diff
prefect (https://github.com/PrefectHQ/prefect)
+ error[invalid-argument-type] src/integrations/prefect-dask/tests/test_task_runners.py:193:17: Argument is incorrect: Expected `StateType`, found `Literal[StateType.COMPLETED]`
```

This is confusing. There are two definitions
([one](https://github.com/PrefectHQ/prefect/blob/74d8cd93eef68600d0c193fa8c4513cf9ac7fdb8/src/prefect/client/schemas/objects.py#L89-L100),
[two](https://github.com/PrefectHQ/prefect/blob/main/src/prefect/server/schemas/states.py#L40))
of the `StateType` enum. Here, we're trying to assign one to the other.
I don't think that should be allowed, so this is a true positive (?).

```diff
python-htmlgen (https://github.com/srittau/python-htmlgen)
+ error[invalid-assignment] test_htmlgen/form.py:51:9: Object of type `str` is not assignable to attribute `autocomplete` of type `Autocomplete | None`
+ error[invalid-assignment] test_htmlgen/video.py:38:9: Object of type `str` is not assignable to attribute `preload` of type `Preload | None`
```

True positives. [The stubs are
wrong](https://github.com/srittau/python-htmlgen/blob/01e3b911ac282d067850bb324b913e3594bc0e23/htmlgen/form.pyi#L8-L10).
These should not contain type annotations, but rather just `OFF = ...`.

```diff
rotki (https://github.com/rotki/rotki)
+ error[invalid-argument-type] rotkehlchen/tests/unit/test_serialization.py:62:30: Argument to bound method `deserialize` is incorrect: Expected `str`, found `Literal[15]`
```

New true positive.

```diff
vision (https://github.com/pytorch/vision)
+ error[unresolved-attribute] test/test_extended_models.py:302:17: Type `type[WeightsEnum]` has no attribute `DEFAULT`
+ error[unresolved-attribute] test/test_extended_models.py:302:58: Type `type[WeightsEnum]` has no attribute `DEFAULT`
```

Also new true positives. No `DEFAULT` member exists on `WeightsEnum`.
2025-07-15 21:31:53 +02:00
Dhruv Manilawala 22177e6915 [ty] Surface matched overload diagnostic directly (#18452)
## Summary

This PR resolves the way diagnostics are reported for an invalid call to
an overloaded function.

If any of the steps in the overload call evaluation algorithm yields a
matching overload but it's type checking that failed, the
`no-matching-overload` diagnostic is incorrect because there is a
matching overload, it's the arguments passed that are invalid as per the
signature. So, this PR improves that by surfacing the diagnostics on the
matching overload directly.

It also provides additional context, specifically the matching overload
where this error occurred and other non-matching overloads. Consider the
following example:

```py
from typing import overload


@overload
def f() -> None: ...
@overload
def f(x: int) -> int: ...
@overload
def f(x: int, y: int) -> int: ...
def f(x: int | None = None, y: int | None = None) -> int | None:
    return None


f("a")
```

We get:

<img width="857" alt="Screenshot 2025-06-18 at 11 07 10"
src="https://github.com/user-attachments/assets/8dbcaf13-2a74-4661-aa94-1225c9402ea6"
/>


## Test Plan

Update test cases, resolve existing todos and validate the updated
snapshots.
2025-06-20 08:36:49 +05:30
Dhruv Manilawala c7e020df6b [ty] Filter overloads based on Any / Unknown (#18607)
## Summary

Closes: astral-sh/ty#552

This PR adds support for step 5 of the overload call evaluation
algorithm which specifies:

> For all arguments, determine whether all possible materializations of
the argument’s type are
> assignable to the corresponding parameter type for each of the
remaining overloads. If so,
> eliminate all of the subsequent remaining overloads.

The algorithm works in two parts:

1. Find out the participating parameter indexes. These are the
parameters that aren't gradual equivalent to one or more parameter types
at the same index in other overloads.
2. Loop over each overload and check whether that would be the _final_
overload for the argument types i.e., the remaining overloads will never
be matched against these argument types

For step 1, the participating parameter indexes are computed by just
comparing whether all the parameter types at the corresponding index for
all the overloads are **gradual equivalent**.

The step 2 of the algorithm used is described in [this
comment](https://github.com/astral-sh/ty/issues/552#issuecomment-2969165421).

## Test Plan

Update the overload call tests.
2025-06-17 15:35:09 +05:30