Skip to content

Commit 03cdec6

Browse files
committed
ignore truthy while statements only if literals are involved
1 parent eb6516b commit 03cdec6

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

mypy/checker.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5058,12 +5058,15 @@ def _filter(body: Block | None) -> bool:
50585058

50595059
if if_map is None:
50605060
if stmt.while_stmt:
5061-
self.msg.redundant_condition_in_while(expr)
5061+
self.msg.redundant_condition_in_while(False, expr)
50625062
elif not _filter(body):
50635063
self.msg.redundant_condition_in_if(False, expr)
50645064

5065-
if else_map is None and not stmt.while_stmt:
5066-
if not (isinstance(body.body[0], ReturnStmt) or _filter(stmt.else_body)):
5065+
if else_map is None:
5066+
if stmt.while_stmt:
5067+
if not is_true_literal(expr):
5068+
self.msg.redundant_condition_in_while(True, expr)
5069+
elif not (_filter(stmt.else_body) or isinstance(body.body[0], ReturnStmt)):
50675070
self.msg.redundant_condition_in_if(True, expr)
50685071

50695072
def visit_while_stmt(self, s: WhileStmt) -> None:

mypy/messages.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2091,8 +2091,8 @@ def redundant_condition_in_comprehension(self, truthiness: bool, context: Contex
20912091
def redundant_condition_in_if(self, truthiness: bool, context: Context) -> None:
20922092
self.redundant_expr("If condition", truthiness, context)
20932093

2094-
def redundant_condition_in_while(self, context: Context) -> None:
2095-
self.redundant_expr("While condition", False, context)
2094+
def redundant_condition_in_while(self, truthiness: bool, context: Context) -> None:
2095+
self.redundant_expr("While condition", truthiness, context)
20962096

20972097
def redundant_expr(self, description: str, truthiness: bool, context: Context) -> None:
20982098
self.fail(

test-data/unit/check-isinstance.test

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3078,6 +3078,10 @@ while True:
30783078
while False: # E: While condition is always false
30793079
...
30803080

3081+
y = None
3082+
while y is None: # E: While condition is always true
3083+
...
3084+
30813085
[builtins fixtures/bool.pyi]
30823086

30833087
[case testNoRedundantExpressionWarningsForUsagesOfTYPECHECKING]

0 commit comments

Comments
 (0)