Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[red-knot] Support typing.TYPE_CHECKING #14952

Merged
merged 1 commit into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Known constants

## `typing.TYPE_CHECKING`

This constant is `True` when in type-checking mode, `False` otherwise. The symbol is defined to be
`False` at runtime. In typeshed, it is annotated as `bool`. This test makes sure that we infer
`Literal[True]` for it anyways.

### Basic

```py
from typing import TYPE_CHECKING
import typing

reveal_type(TYPE_CHECKING) # revealed: Literal[True]
reveal_type(typing.TYPE_CHECKING) # revealed: Literal[True]
```

### Aliased

Make sure that we still infer the correct type if the constant has been given a different name:

```py
from typing import TYPE_CHECKING as TC

reveal_type(TC) # revealed: Literal[True]
```

### Must originate from `typing`

Make sure we only use our special handling for `typing.TYPE_CHECKING` and not for other constants
with the same name:

```py path=constants.py
TYPE_CHECKING: bool = False
```

```py
from constants import TYPE_CHECKING

reveal_type(TYPE_CHECKING) # revealed: bool
```

### `typing_extensions` re-export

This should behave in the same way as `typing.TYPE_CHECKING`:

```py
from typing_extensions import TYPE_CHECKING

reveal_type(TYPE_CHECKING) # revealed: Literal[True]
```
8 changes: 8 additions & 0 deletions crates/red_knot_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,14 @@ fn symbol_by_id<'db>(db: &'db dyn Db, scope: ScopeId<'db>, symbol: ScopedSymbolI

/// Shorthand for `symbol_by_id` that takes a symbol name instead of an ID.
fn symbol<'db>(db: &'db dyn Db, scope: ScopeId<'db>, name: &str) -> Symbol<'db> {
// We don't need to check for `typing_extensions` here, because `typing_extensions.TYPE_CHECKING`
// is just a re-export of `typing.TYPE_CHECKING`.
if name == "TYPE_CHECKING"
&& file_to_module(db, scope.file(db)).is_some_and(|module| module.name() == "typing")
{
return Symbol::Type(Type::BooleanLiteral(true), Boundness::Bound);
}

let table = symbol_table(db, scope);
table
.symbol_id_by_name(name)
Expand Down
Loading