Skip to content

Commit 6ac318c

Browse files
committed
update documents
1 parent cc66b2c commit 6ac318c

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

crates/ty_python_semantic/resources/mdtest/public_types.md

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,6 @@ def outer() -> None:
2828

2929
# This call would observe `x` as `B`.
3030
inner()
31-
32-
def outer(x: A | None):
33-
if x is not None:
34-
def inner() -> None:
35-
reveal_type(x) # revealed: A
36-
inner()
3731
```
3832

3933
Similarly, if control flow in the outer scope can split, the public type of `x` should reflect that:
@@ -169,6 +163,27 @@ def f0() -> None:
169163
f1()
170164
```
171165

166+
## Narrowing
167+
168+
In general, it is not safe to narrow the public type of a symbol using constraints introduced in an
169+
outer scope (because the symbol's value may have changed by the time the lazy scope is actually
170+
evaluated), but they can be applied if there is no reassignment of the symbol.
171+
172+
```py
173+
def outer(x: A | None):
174+
if x is not None:
175+
def inner() -> None:
176+
reveal_type(x) # revealed: A | None
177+
inner()
178+
x = None
179+
180+
def outer(x: A | None):
181+
if x is not None:
182+
def inner() -> None:
183+
reveal_type(x) # revealed: A
184+
inner()
185+
```
186+
172187
## At module level
173188

174189
The behavior is the same if the outer scope is the global scope of a module:
@@ -231,8 +246,8 @@ def _():
231246

232247
### Shadowing
233248

234-
Similarly, since we do not analyze control flow in the outer scope here, we assume that `inner()`
235-
could be called between the two assignments to `x`:
249+
Since we do not analyze control flow in the outer scope here, we assume that `inner()` could be
250+
called between the two assignments to `x`:
236251

237252
```py
238253
def outer() -> None:

crates/ty_python_semantic/src/place.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -769,6 +769,8 @@ fn place_by_id<'db>(
769769
// stubs would result in `IOError` being a union of `OSError` and `Unknown`, which
770770
// leads to all sorts of downstream problems. Similarly, type variables are often
771771
// defined as `_T = TypeVar("_T")`, without being declared.
772+
// Also, if the scope is private, such as a function scope,
773+
// meaning that the place cannot be rewritten from elsewhere, we do not union with `Unknown`.
772774

773775
inferred.into()
774776
} else {

0 commit comments

Comments
 (0)