Skip to content

Commit b73339e

Browse files
committed
feat: Support flake8-lazy style relative imports in __lazy_modules__
1 parent edc1064 commit b73339e

3 files changed

Lines changed: 172 additions & 0 deletions

File tree

‎flake8_type_checking/checker.py‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,104 @@ def visit_Constant(self, node: ast.Constant) -> None:
293293
if self._in__lazy_modules__declaration and isinstance(node.value, str):
294294
self.lazy_modules.add(node.value)
295295

296+
def relative_import_level_minus_one(self, expr: ast.AST) -> int | None:
297+
"""
298+
Determine the relative import level of a flake8-lazy style relative import.
299+
300+
This expects being handed an expression of the form:
301+
302+
__spec__.parent
303+
304+
Or:
305+
306+
spec__.parent.rsplit(".", 1)[0]
307+
308+
Or the type-safe version:
309+
310+
(spec__.parent or "").rsplit(".", 1)[0]
311+
312+
Based on any of these expression we need to determine the
313+
level of the relative import this is supposed to target.
314+
315+
In order to avoid adding one to the integer we retrieve from
316+
the AST only to subtract it again in the code that uses it,
317+
we directly return the level minus one.
318+
319+
For any other expression this will return `None`.
320+
"""
321+
match expr:
322+
# Simple case for a single level
323+
# Matches `__spec__.parent`
324+
case ast.Attribute(
325+
value=ast.Name(id='__spec__'),
326+
attr='parent',
327+
):
328+
return 0
329+
330+
# Complex case for any higher level
331+
case ast.Subscript(
332+
value=ast.Call(
333+
func=ast.Attribute(
334+
value=(
335+
# Matches `spec__.parent.rsplit(".", 1)[0]`
336+
ast.Attribute(value=ast.Name(id='__spec__'), attr='parent')
337+
# Matches `(spec__.parent or "").rsplit(".", 1)[0]`
338+
| ast.BoolOp(
339+
op=ast.Or(),
340+
values=[
341+
ast.Attribute(value=ast.Name(id='__spec__'), attr='parent'),
342+
ast.Constant(value=''),
343+
],
344+
)
345+
),
346+
attr='rsplit',
347+
),
348+
args=[
349+
ast.Constant(value='.'),
350+
ast.Constant(value=int() as level_minus_one),
351+
],
352+
keywords=[],
353+
),
354+
slice=ast.Constant(value=0),
355+
):
356+
return level_minus_one
357+
358+
case _:
359+
return None
360+
361+
def visit_JoinedStr(self, node: ast.JoinedStr) -> None:
362+
"""
363+
Record all flake8-lazy style relative import names.
364+
365+
The motivation behind this style is that flake8 does not provide
366+
us with any sort of information about the project's structure and
367+
since `__lazy_modules__` needs to contain the absolute name in order
368+
to match the relative name, there is no way for us statically link
369+
the two together, unless we use this f-string based approach.
370+
"""
371+
if not self._in__lazy_modules__declaration:
372+
return
373+
374+
match node:
375+
case ast.JoinedStr(
376+
values=[
377+
ast.FormattedValue(
378+
value=expr,
379+
conversion=-1,
380+
format_spec=None,
381+
),
382+
ast.Constant(value=str() as module),
383+
],
384+
) if module.startswith('.'):
385+
level_minus_one = self.relative_import_level_minus_one(expr)
386+
if level_minus_one is None:
387+
return
388+
389+
if level_minus_one:
390+
module = '.' * level_minus_one + module
391+
392+
self.lazy_modules.add(module)
393+
296394

297395
class PydanticMixin:
298396
"""

‎tests/test_import_visitors.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,41 @@ def _get_lazy_imports(example: str) -> list[str]:
134134
),
135135
]
136136

137+
relative_dunder_lazy_ignore_imports = [
138+
(
139+
textwrap.dedent('''
140+
__lazy_modules__ = [f"{__spec__.parent}.a"]
141+
from .a import lazy, also_lazy
142+
from ..a import eager
143+
'''),
144+
['.a.lazy', '.a.also_lazy'],
145+
f,
146+
),
147+
(
148+
textwrap.dedent('''
149+
__lazy_modules__ = [
150+
f"{__spec__.parent.rsplit('.', 1)[0]}.a"
151+
]
152+
from .a import eager
153+
from ..a import lazy
154+
'''),
155+
['..a.lazy'],
156+
f,
157+
),
158+
(
159+
textwrap.dedent('''
160+
__lazy_modules__ = [
161+
f"{(__spec__.parent or '').rsplit('.', 2)[0]}.a"
162+
]
163+
from .a import eager
164+
from ..a import also_eager
165+
from ...a import lazy
166+
'''),
167+
['...a.lazy'],
168+
f,
169+
),
170+
]
171+
137172
if sys.version_info >= (3, 15):
138173
lazy_imports = [
139174
# ast.Import
@@ -154,6 +189,7 @@ def _get_lazy_imports(example: str) -> list[str]:
154189
*venv_imports,
155190
*typing_block_imports,
156191
*dunder_lazy_ignore_imports,
192+
*relative_dunder_lazy_ignore_imports,
157193
*lazy_imports,
158194
]
159195

‎tests/test_tc001_to_tc003.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,44 @@ def get_tc_001_to_003_tests(import_: str, ERROR: str) -> L:
134134
(f'__lazy_modules__=["{import_}"]\nfrom {import_} import constants as x\ny:x', set()),
135135
]
136136

137+
if ERROR == TC001:
138+
# flake8-lazy style relative imports
139+
lazy_imports.extend(
140+
(
141+
(
142+
textwrap.dedent(f'''
143+
__lazy_modules__ = [f"{{__spec__.parent}}.{import_}"]
144+
from .{import_} import constants as x
145+
146+
y: x
147+
'''),
148+
set(),
149+
),
150+
(
151+
textwrap.dedent(f'''
152+
__lazy_modules__ = [
153+
f"{{__spec__.parent.rsplit('.', 1)[0]}}.{import_}"
154+
]
155+
from ..{import_} import x
156+
157+
y: x
158+
'''),
159+
set(),
160+
),
161+
(
162+
textwrap.dedent(f'''
163+
__lazy_modules__ = [
164+
f"{{(__spec__.parent or '').rsplit('.', 2)[0]}}.{import_}"
165+
]
166+
from ...{import_} import x
167+
168+
y: x
169+
'''),
170+
set(),
171+
),
172+
)
173+
)
174+
137175
if sys.version_info >= (3, 15):
138176
lazy_imports.extend(
139177
(

0 commit comments

Comments
 (0)