Skip to content

Commit f122273

Browse files
oconnor663AlexWaygood
authored andcommitted
[ty] perform type narrowing for places marked global too (#19381)
Fixes astral-sh/ty#311.
1 parent f165687 commit f122273

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
@@ -6377,7 +6377,13 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
63776377
if let Some(name) = expr.as_name() {
63786378
if let Some(symbol_id) = place_table.place_id_by_name(name) {
63796379
if self.skip_non_global_scopes(file_scope_id, symbol_id) {
6380-
return global_symbol(self.db(), self.file(), name);
6380+
return global_symbol(self.db(), self.file(), name).map_type(|ty| {
6381+
self.narrow_place_with_applicable_constraints(
6382+
expr,
6383+
ty,
6384+
&constraint_keys,
6385+
)
6386+
});
63816387
}
63826388
is_nonlocal_binding = self
63836389
.index

0 commit comments

Comments
 (0)