Skip to content

Commit 05cfabd

Browse files
committed
Don't flag intentionally empty generators unreachable
1 parent 89ad125 commit 05cfabd

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

mypy/checker.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@
132132
Var,
133133
WhileStmt,
134134
WithStmt,
135+
YieldExpr,
135136
is_final_node,
136137
)
137138
from mypy.options import Options
@@ -1063,6 +1064,20 @@ def enter_attribute_inference_context(self) -> Iterator[None]:
10631064
yield None
10641065
self.inferred_attribute_types = old_types
10651066

1067+
def _is_empty_generator(self, func: FuncItem) -> bool:
1068+
"""
1069+
Checks whether a function's body is 'return; yield' (the yield being added only
1070+
to promote the function into a generator).
1071+
"""
1072+
return (
1073+
len(body := func.body.body) == 2
1074+
and isinstance(ret_stmt := body[0], ReturnStmt)
1075+
and ret_stmt.expr is None
1076+
and isinstance(expr_stmt := body[1], ExpressionStmt)
1077+
and isinstance(yield_expr := expr_stmt.expr, YieldExpr)
1078+
and yield_expr.expr is None
1079+
)
1080+
10661081
def check_func_def(
10671082
self, defn: FuncItem, typ: CallableType, name: str | None, allow_empty: bool = False
10681083
) -> None:
@@ -1240,7 +1255,7 @@ def check_func_def(
12401255
# have no good way of doing this.
12411256
#
12421257
# TODO: Find a way of working around this limitation
1243-
if len(expanded) >= 2:
1258+
if len(expanded) >= 2 or self._is_empty_generator(item):
12441259
self.binder.suppress_unreachable_warnings()
12451260
self.accept(item.body)
12461261
unreachable = self.binder.is_unreachable()

0 commit comments

Comments
 (0)