Skip to content

Commit 508823f

Browse files
committed
update documents
1 parent cc66b2c commit 508823f

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

crates/ty_python_semantic/resources/mdtest/public_types.md

Lines changed: 25 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,29 @@ 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+
class A: ...
174+
175+
def outer(x: A | None):
176+
if x is not None:
177+
def inner() -> None:
178+
reveal_type(x) # revealed: A | None
179+
inner()
180+
x = None
181+
182+
def outer(x: A | None):
183+
if x is not None:
184+
def inner() -> None:
185+
reveal_type(x) # revealed: A
186+
inner()
187+
```
188+
172189
## At module level
173190

174191
The behavior is the same if the outer scope is the global scope of a module:
@@ -231,8 +248,8 @@ def _():
231248

232249
### Shadowing
233250

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`:
251+
Since we do not analyze control flow in the outer scope here, we assume that `inner()` could be
252+
called between the two assignments to `x`:
236253

237254
```py
238255
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)