Patchwork [6,of,8,v2] import-checker: ignore nested imports

login
register
mail settings
Submitter Augie Fackler
Date Nov. 17, 2013, 9:37 p.m.
Message ID <595f370199e52637504a.1384724244@hit-nxdomain.opendns.com>
Download mbox | patch
Permalink /patch/3040/
State Accepted
Commit 957b43371928c688313b912d3739420fee219610
Headers show

Comments

Augie Fackler - Nov. 17, 2013, 9:37 p.m.
# HG changeset patch
# User Augie Fackler <raf@durin42.com>
# Date 1384712861 18000
#      Sun Nov 17 13:27:41 2013 -0500
# Node ID 595f370199e52637504a25be843397c3fdd7a324
# Parent  e5d51fa51abacc03764b60ed76e330cfed6901cf
import-checker: ignore nested imports

Patch

diff --git a/contrib/import-checker.py b/contrib/import-checker.py
--- a/contrib/import-checker.py
+++ b/contrib/import-checker.py
@@ -71,15 +71,23 @@ 
 
 stdlib_modules = set(list_stdlib_modules())
 
-def imported_modules(source):
+def imported_modules(source, ignore_nested=False):
     """Given the source of a file as a string, yield the names
     imported by that file.
 
-    >>> list(imported_modules(
+    >>> sorted(imported_modules(
     ...         'import foo ; from baz import bar; import foo.qux'))
-    ['foo', 'baz.bar', 'foo.qux']
+    ['baz.bar', 'foo', 'foo.qux']
+    >>> sorted(imported_modules(
+    ... '''import foo
+    ... def wat():
+    ...     import bar
+    ... ''', ignore_nested=True))
+    ['foo']
     """
     for node in ast.walk(ast.parse(source)):
+        if ignore_nested and getattr(node, 'col_offset', 0) > 0:
+            continue
         if isinstance(node, ast.Import):
             for n in node.names:
                 yield n.name
@@ -171,7 +179,8 @@ 
         f = open(source_path)
         modname = dotted_name_of_path(source_path)
         src = f.read()
-        used_imports[modname] = sorted(imported_modules(src))
+        used_imports[modname] = sorted(
+            imported_modules(src, ignore_nested=True))
         for error in verify_stdlib_on_own_line(src):
             any_errors = True
             print source_path, error