Commit Graph
16 Commits
Author SHA1 Message Date
Carl Meyer f076cb67a1 [ty] Preserve exception types after tuple truthiness checks (#30018)
Checking that a tuple of exception classes is nonempty can make ty
forget which exceptions it matches in `isinstance`, `issubclass`, and
`except`. Use the positive members of the narrowed type to retain the
exception types. Keep failed checks conservative when an intersection
excludes some class-info values, and cap the work of distributing
intersections over unions.

Closes astral-sh/ty#4895.

## Test plan

Ran ty on synthetic flat and nested class-info intersections with eleven
union-valued tuple members. Both checks completed promptly.

## Ecosystem report

The public ecosystem run at `2be8ff992a286ee82fca80daf4fad88cac7bb305`
found eight expected diagnostic removals from more precise exception
inference and class narrowing. Apprise loses one valid
`redundant-condition-strict` warning because the existing truthiness
evaluator treats the correctly narrowed union as ambiguous. The warning
loss is accepted for this PR. [Full ecosystem
report](https://github.com/astral-sh/ruff/pull/30018#issuecomment-6636630648)
2026-11-04 11:33:17 -08: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 9e3ea63fb4 [ty] Avoid panic when negating dynamic type aliases (#29427)
ty could panic when an exception handler used a negated alias whose
value is gradual, such as `Not[Dynamic]` for `type Dynamic = Any`.
Negating aliases now applies the same normalization as other negative
intersection elements, so an alias of `Any` simplifies to `Any`. The
builder retains unsimplified negative aliases to preserve recursive
self-references.

Closes astral-sh/ty#4729.
2026-10-15 17:27:32 -07:00
Charlie MarshandCarl Meyer c64c7d6dad [ty] Model try exception flow with operation checkpoints (#27471)
## Summary

Previously, we treated every definition inside a `try` block as a
possible exception point, allowing handlers to observe states that could
never occur:

```py
def may_raise(value: object) -> None: ...

state = 0
try:
    may_raise(state := 1)
except:
    reveal_type(state)
    # Before: Literal[0, 1]
    # After: Literal[1]
```

We now record exception checkpoints immediately before operations that
can raise, after evaluating their operands. This includes calls,
imports, name lookups, attribute access, operators, iteration, and other
potentially raising operations.

(This is based on Carl's draft: #27221.)

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
2026-08-12 17:11:48 -04:00
Carl Meyer 7f16205240 [ty] Project intersections in to_instance (#26892)
## Summary

Support `to_instance` on intersection types instead of returning a
`Todo` type.

This is split out of #26712 (for
[astral-sh/ty#3557](https://github.com/astral-sh/ty/issues/3557)).

We project instantiable positive elements of the intersection into an
instance intersection, discarding non-instantiable elements and negative
elements. This is a sound over-approximation, which is also the case for
several other existing arms of `to_instance`, and is fine for use in
type inference.

However, this did expose one case where we used `to_instance` on the
"target" side of an assignability relation. In that position an
over-approximation is _not_ sound; it can cause us to claim an incorrect
relation to be true. This was a pre-existing issue (for all existing
arms of `to_instance` that returned an over-approximation), but adding
intersections exposed a new case of it in the ecosystem.

To fix that, `to_instance` now returns an enum distinguishing exact
projections (safe to use everywhere, including in relation target
position) from over-approximating projections (safe to use in
inference). In general, an exact projection would be one that
round-trips precisely back through `to_meta_type`, whereas an
over-approximation would be one that results in a wider type when
converted back via `to_meta_type`.

We add a new `to_instance_approximation` method which collapses this
distinction (same as the old `to_instance`). This adds noise to the PR
diff (converting most existing uses of `to_instance` to
`to_instance_approximation`) but seems like better API clarity for
future.

This clear distinction between exact and over-approximating
`to_instance` allowed simplifying what was previously a confusing set of
special cases in the relation code, which were effectively attempting to
model the same distinction in an ad-hoc way by matching on specific
types.)

## Test plan

- Added an exception-handling mdtest covering multiple positive class
constraints, an exact-class negative/proper-subclass case, and the mixed
`except A and B` path.
- Added generic narrowing and subtype regressions covering direct and
nested intersections and constrained type variables; updated the
existing decorator fixtures to expect the newly exposed invalid-return
diagnostic.
2026-07-16 20:25:41 -07:00
Carl Meyer 38fc8c0ce5 [ty] more precise exception types when catching a union (#25076)
## Summary

Fixes https://github.com/astral-sh/ty/issues/3432.

Currently if you `except some_var as e:` where `some_var` is a union
type, we aren't able to extract a precise type for `e` from it; this PR
adds that ability.

## Test Plan

Added mdtest.
2026-05-10 00:37:23 +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
bd4e6f3663 Update prek dependencies (#22868)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
2026-01-26 10:35:50 +00:00
renovate[bot]andMicha Reiser a1c3f16358 Update pre-commit dependencies (#22281)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Micha Reiser <micha@reiser.io>
2025-12-29 17:11:28 +00:00
Alex Waygood 3065f8dbbc [ty] Improve diagnostics for invalid exceptions (#21475)
## Summary

Not a high-priority task... but it _is_ a weekend :P

This PR improves our diagnostics for invalid exceptions. Specifically:
- We now give a special-cased ``help: Did you mean
`NotImplementedError`` subdiagnostic for `except NotImplemented`, `raise
NotImplemented` and `raise <EXCEPTION> from NotImplemented`
- If the user catches a tuple of exceptions (`except (foo, bar, baz):`)
and multiple elements in the tuple are invalid, we now collect these
into a single diagnostic rather than emitting a separate diagnostic for
each tuple element
- The explanation of why the `except`/`raise` was invalid ("must be a
`BaseException` instance or `BaseException` subclass", etc.) is
relegated to a subdiagnostic. This makes the top-level diagnostic
summary much more concise.

## Test Plan

Lots of snapshots. And here's some screenshots:

<details>
<summary>Screenshots</summary>

<img width="1770" height="1520" alt="image"
src="https://github.com/user-attachments/assets/7f27fd61-c74d-4ddf-ad97-ea4fd24d06fd"
/>

<img width="1916" height="1392" alt="image"
src="https://github.com/user-attachments/assets/83e5027c-8798-48a6-a0ec-1babfc134000"
/>

<img width="1696" height="588" alt="image"
src="https://github.com/user-attachments/assets/1bc16048-6eb4-4dfa-9ace-dd271074530f"
/>

</details>
2025-11-15 22:12:00 +00:00
Douglas CreagerandCarl Meyer dc84645c36 [ty] Use separate Rust types for bound and unbound type variables (#19796)
This PR creates separate Rust types for bound and unbound type
variables, as proposed in https://github.com/astral-sh/ty/issues/926.

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

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
2025-08-11 15:29:58 -04:00
Shunsuke ShibayamaandAlex Waygood ef564094a9 [ty] support del statement and deletion of except handler names (#18593)
## Summary

This PR closes https://github.com/astral-sh/ty/issues/238.

Since `DefinitionState::Deleted` was introduced in #18041, support for
the `del` statement (and deletion of except handler names) is
straightforward.

However, it is difficult to determine whether references to attributes
or subscripts are unresolved after they are deleted. This PR only
invalidates narrowing by assignment if the attribute or subscript is
deleted.

## Test Plan

`mdtest/del.md` is added.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2025-06-12 07:44:42 -07:00
8729cb208f [ty] Raise invalid-exception-caught even when exception is not captured (#18202)
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
Co-authored-by: Carl Meyer <carl@astral.sh>
2025-05-19 18:13:34 -04:00
Felix Scherz fb589730ef [ty]: Consider a class with a dynamic element in its MRO assignable to any subtype of type (#18205) 2025-05-19 19:30:30 +00:00
Alex Waygood 55df9271ba [ty] Understand homogeneous tuple annotations (#17998) 2025-05-12 22:02:25 -04:00
Micha Reiser b51c4f82ea Rename Red Knot (#17820) 2025-05-03 19:49:15 +02:00