[epic] Pyrefly needs to respect annotations better
Describe the Bug
I noticed recently that Pyrefly is a bit more clever than I think it should be about using inferred types. We implement assignment narrowing, so that if I have
x: object
x = 5
we'll infer the type of x to be Literal[5]. This is probably fine, since Literal[5] <: int where in this case by <: I mean true subtyping (not just assignability).
When we do this, we do at least try to check assignability, but that's actually not acceptable because it causes type erasure in cases where the user is probably explicitly trying to introduce a typed boundary. For example, consider this code:
from typing import *
def f() -> Any: ...
x: int
x = f()
reveal_type(x) # reveals Any
We won't do this in the special case of an annotated assignment, which is (a) a little surprising and inconsistent but also (b) isn't good enough in some cases; my trivial example could have been written x: int = f() but in a lot of code there are multiple assignments and many linters actually dislike duplicated annotations. I believe we absolutely should not be overriding a declared type with a gradual type like this.
On top of that there's a separate collection of bugs where we don't do any checking at all. For example:
from typing import *
def f() -> str: ...
x: int
x = f() # Errors, correctly
reveal_type(x) # Reveals int, which seems like the right behavior and is probably intended
x, y = f(), f() # Errors again, correctly
reveal_type(x) # oops, now it's a `str`
I find it impossible to believe anyone intended this, I think the logic we use here is probably just so poorly organized (probably just hacked into each operation independently) so that most edge cases wind up actually diverging from the happy case. Part of the problem, from a skim, seems to be that in some cases expr_infer_with_hint might wind up throwing errors using the hint but then returning the actual inferred expr type anyway. That might be the right behavior in some cases, but for binding a value to an annotated name it is never the right thing, we should throw an error and then keep the annotated type for downstream code.
I marked this umbrella because I think there is a collection of mostly unrelated bugs and gaps in the logic that probably have independent fixes, and part of the work is to just figure them out. A particularly egregious one for any async codebase is that we pretty much always override the annotated type when there's a type error in an awaited assignment.
Sandbox Link
No response
(Only applicable for extension issues) IDE Information
No response
I would like to work on this
hi @exploratoryprorammer this is an umbrella task that describes a variety of issues, but things haven't been taskified into concrete work items yet
let's wait for @stroxler to create sub-issues for each bug and mark the ones that are self-contained w/ "help wanted"
Hi @yangdanny97. Thanks for the insight. I will be sure to contribute once there are issues with the "help wanted" marker.
This issue has someone assigned, but has not had recent activity for more than 2 weeks.
If you are still working on this issue, please add a comment so everyone knows. Otherwise, please unassign yourself and allow someone else to take over.
Thank you for your contributions!
I'll claim this to do some investigating/prototyping when I have cycles, but unclear if I'll have time to fix the whole thing
I made one fix for the x, y = f(), f() example, putting this back up for grabs
Steven and I dug into this pretty extensively and I wanted to share what we found.
I landed some targeted fixes for the issue, but implementing a general soltuion causes a lot of errors downstream. We tried to come up with a rule that would handle all cases and tested five different approaches and ran them against myprimer. Here's a summary (e is the expr type and m is the annotation type here):
| Approach | New Errors | Fixed | Net |
|---|---|---|---|
| Structural consistency | +295 | -188 | +107 |
| Hybrid (consistency + subtype for unions) | +454 | -198 | +256 |
Flipped subtype m <: e |
+637 | -63 | +574 |
Pure subtype e <: m (two variants) |
~3000 | ? | much worse |
The fundamental issue is that real Python code relies on the expression type after assignment, not the annotation type. Consider:
x: Sequence[int] | str = "hello"
x = get_list() # returns list[int]
x.append(5) # valid at runtime — x IS a list, not a Sequence
Any subtype-based approach keeps Sequence[int] (because list[int] <: Sequence[int]), which then breaks .append(), __setitem__, and every other list-specific method downstream. We saw this blow up across scipy (+120 errors), kornia (+112), spack (+53), spark (+42).
Flipping the subtype direction (m <: e — keep the annotation member if it's a subtype of the expr) seemed clever but was even worse. Protocol relationships and union subtyping let unwanted annotation members leak through — e.g., Buffer getting kept alongside ndarray because ndarray implements the Buffer protocol.
The structural consistency approach, which is an approach that just treats types as equivlant but adapted to gradual types, performed best because it asks the question: "are these structurally the same type, modulo Any?" rather than "is one assignable to the other?" It only changes behavior for same-class types (like list[int] vs list[Any]) and Any expressions, which is exactly the cases where preserving the annotation isn't invasive. For everything else it falls back to the expression type.
Whie the consistency approach is promising (+295/-188), it's not a complete solution. There are some more targeted fixes we can implement and there is a question of if we should do that or if we should refrain from adding complication through targeted fixes.
We're tabling the general solution for now. That said, this is a good candidate for a strict preset in the future. The subtype approach could be gated behind a stricter mode where users opt into tighter annotation enforcement.