Skip to content

Commit

Permalink
Treat type aliases as typing-only expressions (#7968)
Browse files Browse the repository at this point in the history
## 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.
  • Loading branch information
charliermarsh authored Oct 16, 2023
1 parent 8061894 commit b6e75e5
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from __future__ import annotations

from collections.abc import Callable
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from .foo import Record

type RecordOrThings = Record | int | str
type RecordCallback[R: Record] = Callable[[R], None]


def process_record[R: Record](record: R) -> None:
...


class RecordContainer[R: Record]:
def add_record(self, record: R) -> None:
...
6 changes: 4 additions & 2 deletions crates/ruff_linter/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,9 @@ where
if let Some(type_params) = type_params {
self.visit_type_params(type_params);
}
self.visit_expr(value);
// The value in a `type` alias has annotation semantics, in that it's never
// evaluated at runtime.
self.visit_annotation(value);
self.semantic.pop_scope();
self.visit_expr(name);
}
Expand Down Expand Up @@ -1766,7 +1768,7 @@ impl<'a> Checker<'a> {
bound: Some(bound), ..
}) = type_param
{
self.visit_expr(bound);
self.visit_annotation(bound);
}
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/rules/flake8_type_checking/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod tests {
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_12.py"))]
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_13.py"))]
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_14.pyi"))]
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_15.py"))]
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_2.py"))]
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_3.py"))]
#[test_case(Rule::RuntimeImportInTypeCheckingBlock, Path::new("TCH004_4.py"))]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
source: crates/ruff_linter/src/rules/flake8_type_checking/mod.rs
---

0 comments on commit b6e75e5

Please sign in to comment.