Skip to content

Commit fb7f75b

Browse files
committed
Allow imports to be excluded by using the pyright ignore directive.
Closes #18
1 parent a89f072 commit fb7f75b

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

imports.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,18 @@ def get_module_imports(module: pathlib.Path | str | bytes) -> Generator[str]:
155155
>>> list(get_module_imports('from .foo import bar'))
156156
['.foo.bar']
157157
158+
Any names excluded by pyright are also excluded (#18).
159+
160+
>>> list(get_module_imports('import nspkg # ignore[reportMissingImports]\nimport foo'))
161+
['foo']
162+
158163
"""
164+
excluded_lines = excludes(get_module_comments(module))
159165
return (
160166
Import.read(node, alias)
161167
for node in ast.walk(ast.parse(module))
162-
if isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom)
168+
if isinstance(node, (ast.Import, ast.ImportFrom))
169+
and node.lineno not in excluded_lines
163170
for alias in node.names
164171
)
165172

@@ -182,6 +189,17 @@ def get_module_comments(code: bytes | str) -> dict[int, str]:
182189
}
183190

184191

192+
def excludes(comments):
193+
"""
194+
Exclude lines based on comments.
195+
"""
196+
return {
197+
line: comment
198+
for line, comment in comments.items()
199+
if 'ignore[reportMissingImports]' in comment
200+
}
201+
202+
185203
@get_module_comments.register
186204
def _(code: bytes):
187205
return get_module_comments(code.decode('utf-8'))

0 commit comments

Comments
 (0)