Skip to content

Commit

Permalink
Fixes TC004/TC009 emitting too many errors when symbols are redefined.
Browse files Browse the repository at this point in the history
  • Loading branch information
Daverball authored and sondrelg committed Nov 25, 2023
1 parent d54b13c commit 0e48ae8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
9 changes: 8 additions & 1 deletion flake8_type_checking/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1543,9 +1543,16 @@ def used_type_checking_symbols(self) -> Flake8Generator:
else:
lookup_from = use

if scope.lookup(symbol.name, lookup_from):
if scope.lookup(symbol.name, lookup_from, runtime_only=True):
# the symbol is available at runtime so we're fine
continue
elif scope.lookup(symbol.name, lookup_from, runtime_only=False) is not symbol:
# we are being shadowed so no need to emit an error, we can emit an error
# for the shadowed name instead, this relies more heavily on giving us the
# closest match when looking up symbols, so we may sometimes get this wrong
# in cases where the symbol has been redefined within the same scope. But
# the most important case is nested scopes, so this is probably fine.
continue

if symbol.type == 'import':
msg = TC004.format(module=symbol.name)
Expand Down
27 changes: 27 additions & 0 deletions tests/test_tc004.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,33 @@ class X:
"""),
set(),
),
# Inverse Regression test for #131
# handle scopes correctly, so we should get an error for the imports
# in the inner scopes, but not one for the outer scope.
(
textwrap.dedent("""
if TYPE_CHECKING:
from a import Foo
def foo():
if TYPE_CHECKING:
from b import Foo
bar: Foo = Foo()
return bar
class X:
if TYPE_CHECKING:
from b import Foo
bar: Foo = Foo()
"""),
{
'7:0 ' + TC004.format(module='Foo'),
'14:0 ' + TC004.format(module='Foo'),
},
),
# Some more complex scope cases where we shouldn't report a
# runtime use of a typing only symbol, because it is shadowed
# by an inline definition. We use five different symbols
Expand Down

0 comments on commit 0e48ae8

Please sign in to comment.