Skip to content

Commit 70128ef

Browse files
committed
feat: Support relative imports mapping to absolute lazy module names
Since the only adverse outcome for detecting relative lazy imports via `__lazy_modules__` too eagerly is a false negative for that specific import, we can be a lot more forgiving and match both any absolute import names that could map to this relative import and also match other esoteric ways to write relative imports using expressions other than the conventions defined by `flake8-lazy`. This improves interoperability with ruff, which currently does not support `flake8-lazy`'s relative import conventions and generally allows users to be more free in how they handle relative lazy imports with `__lazy_modules__`.
1 parent 98a11e6 commit 70128ef

3 files changed

Lines changed: 120 additions & 5 deletions

File tree

‎flake8_type_checking/checker.py‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ class DunderLazyModulesMixin:
232232

233233
if TYPE_CHECKING:
234234
lazy_modules: set[str]
235+
relative_lazy_modules: set[str]
235236
ignore_dunder_lazy_modules: bool
236237
current_scope: Scope
237238

@@ -384,12 +385,15 @@ def visit_JoinedStr(self, node: ast.JoinedStr) -> None:
384385
) if module.startswith('.'):
385386
level_minus_one = self.relative_import_level_minus_one(expr)
386387
if level_minus_one is None:
388+
# we don't know the exact level, so record as a regular
389+
# name so we perform a suffix match
390+
self.lazy_modules.add(module)
387391
return
388392

389393
if level_minus_one:
390394
module = '.' * level_minus_one + module
391395

392-
self.lazy_modules.add(module)
396+
self.relative_lazy_modules.add(module)
393397

394398

395399
class PydanticMixin:
@@ -754,7 +758,7 @@ class ImportName:
754758
#: Whether or not this import is exempt from TC001-004 checks.
755759
exempt: bool
756760

757-
#: Whether or not this import is lazy
761+
#: Whether or not this import could be lazy
758762
is_lazy: bool | None
759763

760764
@property
@@ -1203,6 +1207,9 @@ def __init__(
12031207
#: A set of modules marked as Python 3.15+ lazy imports
12041208
self.lazy_modules: set[str] = set()
12051209

1210+
#: A set of relative module names detected using flake8-lazy's conventions
1211+
self.relative_lazy_modules: set[str] = set()
1212+
12061213
#: Whether or not __lazy_modules__ declarations should excempt imports
12071214
#: from being flagged by TC001, TC002 or TC003.
12081215
self.ignore_dunder_lazy_modules = ignore_dunder_lazy_modules
@@ -1507,8 +1514,26 @@ def add_import(self, node: Import) -> None: # noqa: C901
15071514
module = '.' * node.level + module
15081515

15091516
# Mark all imported symbols as lazy if the module is lazy
1510-
if not all_lazy and self.lazy_modules and module.rstrip('.') in self.lazy_modules:
1511-
all_lazy = True
1517+
if not all_lazy and (self.lazy_modules or self.relative_lazy_modules):
1518+
module_name = module.rstrip('.')
1519+
if (
1520+
module_name in self.lazy_modules
1521+
or module_name in self.relative_lazy_modules
1522+
or (
1523+
# For relative imports it might match one of the absolute
1524+
# imports as long as it contains at least one dot, we can't
1525+
# prove whether or not the import is lazy, so we err on the
1526+
# side of caution and treat it as if it were lazy, so we
1527+
# don't generate any false positives
1528+
node.level != 0
1529+
and any(
1530+
lazy_module.endswith('.' + module_name.lstrip('.'))
1531+
for lazy_module in self.lazy_modules
1532+
if '.' in lazy_module
1533+
)
1534+
)
1535+
):
1536+
all_lazy = True
15121537
else:
15131538
module = ''
15141539

‎tests/test_import_visitors.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,54 @@ def _get_lazy_imports(example: str) -> list[str]:
169169
),
170170
]
171171

172+
relative_dunder_lazy_ignore_imports_absolute_or_unknown_format = [
173+
# we don't know how absolute import names map to relative ones
174+
# so we have to assume the relative imports are lazy if they could
175+
# match a lazy import.
176+
(
177+
textwrap.dedent('''
178+
__lazy_modules__ = ["my_module.a"]
179+
from .a import lazy, also_lazy
180+
from ..a import still_lazy
181+
'''),
182+
['.a.lazy', '.a.also_lazy', '..a.still_lazy'],
183+
f,
184+
),
185+
# test some other esoteric ways relative imports could show up
186+
(
187+
textwrap.dedent('''
188+
__lazy_modules__ = [f"{parent_module}.a"]
189+
from .a import lazy, also_lazy
190+
from ..a import still_lazy
191+
'''),
192+
['.a.lazy', '.a.also_lazy', '..a.still_lazy'],
193+
f,
194+
),
195+
(
196+
textwrap.dedent('''
197+
__lazy_modules__ = [
198+
parent_module + ".a"
199+
]
200+
from .a import still_lazy
201+
from ..a import lazy
202+
'''),
203+
['.a.still_lazy', '..a.lazy'],
204+
f,
205+
),
206+
(
207+
textwrap.dedent('''
208+
__lazy_modules__ = [
209+
relative_import_name(".a")
210+
]
211+
from .a import still_lazy
212+
from ..a import also_still_lazy
213+
from ...a import lazy
214+
'''),
215+
['.a.still_lazy', '..a.also_still_lazy', '...a.lazy'],
216+
f,
217+
),
218+
]
219+
172220
if sys.version_info >= (3, 15):
173221
lazy_imports = [
174222
# ast.Import
@@ -190,6 +238,7 @@ def _get_lazy_imports(example: str) -> list[str]:
190238
*typing_block_imports,
191239
*dunder_lazy_ignore_imports,
192240
*relative_dunder_lazy_ignore_imports,
241+
*relative_dunder_lazy_ignore_imports_absolute_or_unknown_format,
193242
*lazy_imports,
194243
]
195244

‎tests/test_tc001_to_tc003.py‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,9 @@ def get_tc_001_to_003_tests(import_: str, ERROR: str) -> L:
135135
]
136136

137137
if ERROR == TC001:
138-
# flake8-lazy style relative imports
139138
lazy_imports.extend(
140139
(
140+
# flake8-lazy style relative imports
141141
(
142142
textwrap.dedent(f'''
143143
__lazy_modules__ = [f"{{__spec__.parent}}.{import_}"]
@@ -165,6 +165,47 @@ def get_tc_001_to_003_tests(import_: str, ERROR: str) -> L:
165165
]
166166
from ...{import_} import x
167167
168+
y: x
169+
'''),
170+
set(),
171+
),
172+
# absolute imports mapping to relative imports
173+
(
174+
textwrap.dedent(f'''
175+
__lazy_modules__ = ["my_module.{import_}"]
176+
from .{import_} import x
177+
178+
y: x
179+
'''),
180+
set(),
181+
),
182+
# esoteric relative import formats
183+
(
184+
textwrap.dedent(f'''
185+
parent_module = __spec__.parent
186+
__lazy_modules__ = [f"{{parent_module}}.{import_}"]
187+
from .{import_} import x
188+
189+
y: x
190+
'''),
191+
set(),
192+
),
193+
(
194+
textwrap.dedent(f'''
195+
parent_module = __spec__.parent
196+
__lazy_modules__ = [parent_module + ".{import_}"]
197+
from .{import_} import x
198+
199+
y: x
200+
'''),
201+
set(),
202+
),
203+
(
204+
textwrap.dedent(f'''
205+
from .utils import relative_import
206+
__lazy_modules__ = [relative_import(".{import_}")]
207+
from .{import_} import x
208+
168209
y: x
169210
'''),
170211
set(),

0 commit comments

Comments
 (0)