Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1307,6 +1307,7 @@ def check_func_def(
self.check_typevar_defaults(typ.variables)
expanded = self.expand_typevars(defn, typ)
original_typ = typ
iter_errors = IterationDependentErrors()
for item, typ in expanded:
old_binder = self.binder
self.binder = ConditionalTypeBinder(self.options)
Expand Down Expand Up @@ -1486,14 +1487,7 @@ def check_func_def(
# We suppress reachability warnings for empty generator functions
# (return; yield) which have a "yield" that's unreachable by definition
# since it's only there to promote the function into a generator function.
#
# We also suppress reachability warnings when we use TypeVars with value
# restrictions: we only want to report a warning if a certain statement is
# marked as being suppressed in *all* of the expansions, but we currently
# have no good way of doing this.
#
# TODO: Find a way of working around this limitation
if _is_empty_generator_function(item) or len(expanded) >= 2:
if _is_empty_generator_function(item):
self.binder.suppress_unreachable_warnings()
# When checking a third-party library, we can skip function body,
# if during semantic analysis we found that there are no attributes
Expand All @@ -1507,7 +1501,13 @@ def check_func_def(
or not isinstance(defn, FuncDef)
or defn.has_self_attr_def
):
self.accept(item.body)
if len(expanded) > 1:
with IterationErrorWatcher(
self.msg.errors, iter_errors, collect_revealed_types=False
):
self.accept(item.body)
else:
self.accept(item.body)
unreachable = self.binder.is_unreachable()
if new_frame is not None:
self.binder.pop_frame(True, 0)
Expand Down Expand Up @@ -1603,6 +1603,9 @@ def check_func_def(

self.binder = old_binder

if len(expanded) > 1:
self.msg.iteration_dependent_errors(iter_errors)

def require_correct_self_argument(self, func: Type, defn: FuncDef) -> bool:
func = get_proper_type(func)
if not isinstance(func, CallableType):
Expand Down
3 changes: 3 additions & 0 deletions mypy/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ class IterationErrorWatcher(ErrorWatcher):
making too-hasty reports."""

iteration_dependent_errors: IterationDependentErrors
collect_revealed_types: bool

def __init__(
self,
Expand All @@ -362,6 +363,7 @@ def __init__(
filter_errors: bool | Callable[[str, ErrorInfo], bool] = False,
save_filtered_errors: bool = False,
filter_deprecated: bool = False,
collect_revealed_types: bool = True,
) -> None:
super().__init__(
errors,
Expand All @@ -373,6 +375,7 @@ def __init__(
iteration_dependent_errors.uselessness_errors.append(set())
iteration_dependent_errors.nonoverlapping_types.append({})
iteration_dependent_errors.unreachable_lines.append(set())
self.collect_revealed_types = collect_revealed_types

def on_error(self, file: str, info: ErrorInfo) -> bool:
"""Filter out the "iteration-dependent" errors and notes and store their
Expand Down
2 changes: 1 addition & 1 deletion mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -1778,7 +1778,7 @@ def reveal_type(self, typ: Type, context: Context) -> None:
# The `reveal_type` statement might be visited iteratively due to being
# placed in a loop or so. Hence, we collect the respective types of
# individual iterations so that we can report them all in one step later:
if isinstance(watcher, IterationErrorWatcher):
if isinstance(watcher, IterationErrorWatcher) and watcher.collect_revealed_types:
watcher.iteration_dependent_errors.revealed_types[
(context.line, context.column, context.end_line, context.end_column)
].append(typ)
Expand Down
14 changes: 14 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -2434,6 +2434,20 @@ for x in xs:
y = {} # E: Need type annotation for "y" (hint: "y: dict[<type>, <type>] = ...")
[builtins fixtures/list.pyi]

[case testAvoidFalseUnreachableInLoopWithContrainedTypeVar]
# flags: --warn-unreachable --python-version 3.11
from typing import TypeVar

T = TypeVar("T", int, str)
def f(x: T) -> list[T]:
y = None
while y is None:
if y is None:
y = []
y.append(x)
return y
[builtins fixtures/list.pyi]

[case testAvoidFalseRedundantExprInLoop]
# flags: --enable-error-code redundant-expr --python-version 3.11

Expand Down
16 changes: 3 additions & 13 deletions test-data/unit/check-unreachable-code.test
Original file line number Diff line number Diff line change
Expand Up @@ -1056,11 +1056,7 @@ def test2(x: T2) -> T2:
reveal_type(x) # N: Revealed type is "builtins.str"

if False:
# This is unreachable, but we don't report an error, unfortunately.
# The presence of the TypeVar with values unfortunately currently shuts
# down type-checking for this entire function.
# TODO: Find a way of removing this limitation
reveal_type(x)
reveal_type(x) # E: Statement is unreachable

return x

Expand All @@ -1074,20 +1070,14 @@ class Test3(Generic[T2]):
reveal_type(self.x) # N: Revealed type is "builtins.str"

if False:
# Same issue as above
reveal_type(self.x)
reveal_type(self.x) # E: Statement is unreachable


class Test4(Generic[T3]):
def __init__(self, x: T3):
# https://github.com/python/mypy/issues/9456
# On TypeVars with value restrictions, we currently have no way
# of checking a statement for all the type expansions.
# Thus unreachable warnings are disabled
if x and False:
pass
# This test should fail after this limitation is removed.
if False and x:
if False and x: # E: Right operand of "and" is never evaluated
pass

[builtins fixtures/isinstancelist.pyi]
Expand Down