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.
Closesastral-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)
## 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.
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.
Closesastral-sh/ty#4729.
## 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>
## 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.
## 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.
- 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
## 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>
## 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>