Skip to content

Commit b6e75e5

Browse files
Treat type aliases as typing-only expressions (#7968)
## Summary Given `type RecordOrThings = Record | int | str`, the right-hand side won't be evaluated at runtime. Same goes for `Record` in `type RecordCallback[R: Record] = Callable[[R], None]`. This PR modifies the visitation logic to treat them as typing-only. Closes #7966.
1 parent 8061894 commit b6e75e5

File tree

4 files changed

+28
-2
lines changed

4 files changed

+28
-2
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from __future__ import annotations
2+
3+
from collections.abc import Callable
4+
from typing import TYPE_CHECKING
5+
6+
if TYPE_CHECKING:
7+
from .foo import Record
8+
9+
type RecordOrThings = Record | int | str
10+
type RecordCallback[R: Record] = Callable[[R], None]
11+
12+
13+
def process_record[R: Record](record: R) -> None:
14+
...
15+
16+
17+
class RecordContainer[R: Record]:
18+
def add_record(self, record: R) -> None:
19+
...

crates/ruff_linter/src/checkers/ast/mod.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,9 @@ where
580580
if let Some(type_params) = type_params {
581581
self.visit_type_params(type_params);
582582
}
583-
self.visit_expr(value);
583+
// The value in a `type` alias has annotation semantics, in that it's never
584+
// evaluated at runtime.
585+
self.visit_annotation(value);
584586
self.semantic.pop_scope();
585587
self.visit_expr(name);
586588
}
@@ -1766,7 +1768,7 @@ impl<'a> Checker<'a> {
17661768
bound: Some(bound), ..
17671769
}) = type_param
17681770
{
1769-
self.visit_expr(bound);
1771+
self.visit_annotation(bound);
17701772
}
17711773
}
17721774
}

crates/ruff_linter/src/rules/flake8_type_checking/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ mod tests {
2222
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_12.py"))]
2323
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_13.py"))]
2424
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_14.pyi"))]
25+
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_15.py"))]
2526
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_2.py"))]
2627
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_3.py"))]
2728
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_4.py"))]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
source: crates/ruff_linter/src/rules/flake8_type_checking/mod.rs
3+
---
4+

0 commit comments

Comments
 (0)