Skip to content

Commit 153d3c6

Browse files
carljmsecond-ed
authored andcommitted
[ty] don't mark entire type-alias scopes as Deferred (astral-sh#20086)
## Summary This has been here for awhile (since our initial PEP 695 type alias support) but isn't really correct. The right-hand-side of a PEP 695 type alias is a distinct scope, and we don't mark it as an "eager" nested scope, so it automatically gets "deferred" resolution of names from outer scopes (just like a nested function). Thus it's redundant/unnecessary for us to use `DeferredExpressionState::Deferred` for resolving that RHS expression -- that's for deferring resolution of individual names within a scope. Using it here causes us to wrongly ignore applicable outer-scope narrowing. ## Test Plan Added mdtest that failed before this PR (the second snippet -- the first snippet always passed.)
1 parent 16b34a9 commit 153d3c6

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

crates/ty_python_semantic/resources/mdtest/pep695_type_aliases.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,32 @@ def f(x: T):
7575
reveal_type(b) # revealed: str
7676
```
7777

78+
## Scoping
79+
80+
PEP 695 type aliases delay runtime evaluation of their right-hand side, so they are a lazy (not
81+
eager) nested scope.
82+
83+
```py
84+
type Alias = Foo | str
85+
86+
def f(x: Alias):
87+
reveal_type(x) # revealed: Foo | str
88+
89+
class Foo:
90+
pass
91+
```
92+
93+
But narrowing of names used in the type alias is still respected:
94+
95+
```py
96+
def _(flag: bool):
97+
t = int if flag else None
98+
if t is not None:
99+
type Alias = t | str
100+
def f(x: Alias):
101+
reveal_type(x) # revealed: int | str
102+
```
103+
78104
## Generic type aliases
79105

80106
```py

crates/ty_python_semantic/src/types/infer.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2344,7 +2344,7 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
23442344
}
23452345

23462346
fn infer_type_alias(&mut self, type_alias: &ast::StmtTypeAlias) {
2347-
self.infer_annotation_expression(&type_alias.value, DeferredExpressionState::Deferred);
2347+
self.infer_annotation_expression(&type_alias.value, DeferredExpressionState::None);
23482348
}
23492349

23502350
/// If the current scope is a method inside an enclosing class,

0 commit comments

Comments
 (0)