[ty] Detect more invalid partially quoted unions, and improve diagnostics #31321
<!-- generated-comment typing-conformance -->
<!-- report-run:47161351731:1 -->
Typing conformance results
No changes detected ✅
<details>
<summary>Current numbers</summary>
<br>
The percentage of diagnostics emitted that were expected errors held steady at <b>98.60%</b>. The percentage of expected errors that received a diagnostic held steady at <b>98.86%</b>. The number of fully passing files held steady at <b>137/146</b>.
</details>
---
Results for 7bc2d6e · Workflow run
<!-- generated-comment memory -->
<!-- report-run:47161351765:1 -->
Memory usage report
Memory usage unchanged ✅
---
Results for 7bc2d6e · Workflow run
<!-- generated-comment ty-ecosystem -->
<!-- report-run:47161351939:1 -->
ecosystem-analyzer results
No diagnostic changes detected ✅
Full report with detailed diff · Timing results
---
Results for 7bc2d6e · Workflow run
<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->
Merging this PR will degrade performance by 5.96%
❌ 1 regressed benchmark ✅ 362 untouched benchmarks ⏩ 92 skipped benchmarks[^skipped]
[!WARNING]
Please fix the performance issues or acknowledge them on CodSpeed.
Performance Changes
| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ | Walltime | ` simple_script | 16.2 ms | 17.3 ms | -5.96% |
[!TIP]
Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.
---
<sub>Comparing <code>alex/partially-quoted-unions</code> (7bc2d6e) with <code>main</code> (72366af)</sub>
<a href="https://app.codspeed.io/astral-sh/ruff/branches/alex%2Fpartially-quoted-unions?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>
[^skipped]: 92 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
it would be great to also show the definition of the alias here in a secondary annotation, but it's a bit more work; I'll do that in a followup. (It would also be great to have an autofix, but that's also going to be a followup!)
that benchmark has generally been pretty flaky recently, and I don't see any reason why this would cause any regressions, so I disbelieve that there's really a regression here.
I think we need to preserve the distinction between typing.Union and types.UnionType here. We now report unsupported-operator for all three of these on Python 3.13, but they all work at runtime.
from typing import Optional, Union
def f(
x: Optional[int] | "str",
y: Union[int, bytes] | "str",
z: bytes | Optional[int] | "str",
): ...
The limitation mentioned below for typing.Type also applies to e.g. typing.List. We now get new false positives for both of these on Python 3.13.
from typing import List, TypeAlias
Alias: TypeAlias = "str"
def f(x: List[int] | Alias, y: bytes | List[int] | "str"): ...
Both work at runtime.
I realize these are deprecated, but that doesn't mean they aren't still used. I don't think we should cause these false positives until these aliases are actually gone from all supported versions.
I found a case where an operand rejects a string itself but produces a union that accepts one. With Python 3.11 and typing_extensions 4.16, the first of these raises and the second works. We now flag both.
from typing_extensions import TypeAliasType
A = TypeAliasType("A", int)
def f(x: A | "str"): ...
def g(x: A | bytes | "str"): ...
The backport's __or__ returns a typing.Union.
Could we move the help outside the match on scope kind? For example, on Python 3.13 we now diagnose this but only give the unrelated note about lazy evaluation of type parameters.
from typing import TypeAlias
Alias: TypeAlias = "str"
def f[T](x: T, y: int | Alias): ...
There's already a TODO in the mdtest about fixing that note. It seems like we could give the same help for generic and non-generic functions independently of that.
I think the boolean in the parenthetical is backwards? If neither operator accepts the operands, wouldn't dunder_fails be true and we'd skip this match? Maybe just drop the parenthetical?
This PR does two things, "detect more invalid partially-quoted unions" and "improve diagnostics." The second one is great, and I'm all in favor of it. But "catching more cases" I think offers little practical value, and wades into areas where we cannot avoid adding false positives. I don't think we should be emitting this diagnostic in cases which require us to attempt an unreliable heuristic distinction between typing._GenericAlias and types.GenericAlias, or between types.UnionType and typing.Union. I would prefer we scale back the ambition here and keep this diagnostic (which other type checkers don't even attempt, and which I have not seen users express high demand for) as high-confidence as possible, strongly preferring false negatives over false positives. (It seems somewhat ironic that the user-reported issue that prompted looking into this in the first place was a false-positive report, and this PR would respond to that report by making the diagnostic more aggressive and adding some false positives.)
I agree with erring on the side of avoiding false positives for user-defined generics. One cost of this particular heuristic is that we now lose some existing diagnostics on main for fairly common stdlib types. For example, main catches all three of these, and they all raise on Python 3.13.
import re
from collections import deque
from collections.abc import Sequence
def f(
x: deque[int] | "str",
y: Sequence[int] | "str",
z: re.Pattern[bytes] | "str",
): ...
So the approach in this PR adds some true positives, but also adds some false positives and loses some true positives.
AlexWaygood
Summary
On Python 3.13, defining
fbelow raises aTypeError. ty already caught this if you wroteint | "Foo"directly, but missed it when the string came from a PEP 613 type alias.ty now reports
unsupported-operatorand suggests quoting the whole union ("int | Alias") to avoid the error when definingf.Python 3.14 and later defer function annotations by default, but still evaluate the right-hand side of an assignment like
X = list["int" | None]immediately. ty now suggests quoting the whole union there too.The check also now catches string operands combined with enum classes, PEP 695 aliases,
type[int], and existing unions such asint | None. That last case depends on the Python version. On Python 3.13,int | None | "str"fails becauseint | Noneproduces atypes.UnionType. On Python 3.14,int | Noneproduces atyping.Union, which accepts being|'d with the string (implicitly converting the string to a forward reference).This also fixes false positives for user-defined generic classes. Given
class Stream[T]: ...,Stream[bytes]is atyping._GenericAlias, soStream[bytes] | "str"accepts the string as a forward reference.list[bytes]is atypes.GenericAlias, solist[bytes] | "str"raises aTypeError.We don't generally track which kind of generic alias subscripting a class produces. To avoid false positives, therefore, this PR introduces a heuristic where we only assume a generic alias rejects strings if the class being subscripted is one we recognize from
builtinsortypes. This means we'll continue to miss some invalid unions.The distinction also matters in chained unions. For example, Dulwich uses
BufferedIOBase | IO[bytes] | "_GitFile". BecauseIO[bytes]is atyping._GenericAlias, the first|produces atyping.Unioneven before Python 3.14. The second|can therefore accept"_GitFile"as a forward reference. An early version of this PR introduced false positives on this code; distinguishing betweenbuiltinsaliases (that we know aretypes.GenericAliases at runtime) and other aliases helps avoid those new false positives.