Skip to content

Commit

Permalink
Merge pull request #157 from iamibi/support-for-is-true
Browse files Browse the repository at this point in the history
Add support for `if TYPE_CHECKING is True` operation
  • Loading branch information
sondrelg committed Jul 16, 2023
2 parents 6949298 + 7c0288e commit 6d671fa
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
28 changes: 28 additions & 0 deletions flake8_type_checking/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,32 @@ def is_type_checking(self, node: ast.AST) -> bool:
or (self.type_checking_alias is not None and hasattr(node, 'id') and (node.id == self.type_checking_alias))
)

def is_type_checking_true(self, node: ast.Compare) -> bool:
"""An ast.Compare node has a `left`, `ops`, and `comparators` attribute.
Here we want to check whether our node corresponds to
`if TYPE_CHECKING is True`
^ ^ ^
left _______| ops |____ comparators
"""
# Left side should be a TYPE_CHECKING block
if (hasattr(node, 'left') and self.is_type_checking(node.left)) is False:
return False

# Operator should be `is`
if (len(node.ops) == 1 and isinstance(node.ops[0], ast.Is)) is False:
return False

# Right side should be `True`
if (
len(node.comparators) == 1
and isinstance(node.comparators[0], ast.Constant)
and node.comparators[0].value is True
) is False:
return False
return True

def is_true_when_type_checking(self, node: ast.AST) -> bool | Literal['TYPE_CHECKING']:
"""Determine if the node evaluates to True when TYPE_CHECKING is True.
Expand Down Expand Up @@ -515,6 +541,8 @@ def is_true_when_type_checking(self, node: ast.AST) -> bool | Literal['TYPE_CHEC
elif isinstance(node, ast.Constant):
with suppress(Exception):
return bool(literal_eval(node))
elif isinstance(node, ast.Compare) is True and self.is_type_checking_true(node) is True:
return 'TYPE_CHECKING'
return False

def visit_If(self, node: ast.If) -> Any:
Expand Down
10 changes: 9 additions & 1 deletion tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,15 @@ def test_type_checking_block_formats_detected(self):
p: Path
"""
for example in [type_checking, typing_type_checking, alias, aliased_typing]:
typing_type_is_true = """
from typing import TYPE_CHECKING
if TYPE_CHECKING is True:
from pathlib import Path
p: Path
"""
for example in [type_checking, typing_type_checking, alias, aliased_typing, typing_type_is_true]:
assert _get_error(textwrap.dedent(example)) == set()

def test_type_checking_block_with_other_conditions(self):
Expand Down

0 comments on commit 6d671fa

Please sign in to comment.