Skip to content

Commit 809e662

Browse files
committed
[ty] perform type narrowing for places marked global too
This fixes a bug reported at: astral-sh/ty#311 (comment)
1 parent e73a8ba commit 809e662

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

crates/ty_python_semantic/resources/mdtest/scopes/global.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,19 @@ def f():
7171
reveal_type(x) # revealed: Literal[1]
7272
```
7373

74+
Same for an `if` statement:
75+
76+
```py
77+
x: int | None
78+
79+
def f():
80+
# The `global` keyword isn't necessary here, but this is testing that it doesn't get in the way
81+
# of narrowing.
82+
global x
83+
if x == 1:
84+
y: int = x # allowed, because x cannot be None in this branch
85+
```
86+
7487
## `nonlocal` and `global`
7588

7689
A binding cannot be both `nonlocal` and `global`. This should emit a semantic syntax error. CPython

crates/ty_python_semantic/src/types/infer.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5949,7 +5949,13 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
59495949
if let Some(name) = expr.as_name() {
59505950
if let Some(symbol_id) = place_table.place_id_by_name(name) {
59515951
if self.skip_non_global_scopes(file_scope_id, symbol_id) {
5952-
return global_symbol(self.db(), self.file(), name);
5952+
return global_symbol(self.db(), self.file(), name).map_type(|ty| {
5953+
self.narrow_place_with_applicable_constraints(
5954+
expr,
5955+
ty,
5956+
&constraint_keys,
5957+
)
5958+
});
59535959
}
59545960
is_nonlocal_binding = self
59555961
.index

0 commit comments

Comments
 (0)