Show More
@@ -71,15 +71,31 def list_stdlib_modules(): | |||||
71 |
|
71 | |||
72 | stdlib_modules = set(list_stdlib_modules()) |
|
72 | stdlib_modules = set(list_stdlib_modules()) | |
73 |
|
73 | |||
74 | def imported_modules(source): |
|
74 | def imported_modules(source, ignore_nested=False): | |
75 | """Given the source of a file as a string, yield the names |
|
75 | """Given the source of a file as a string, yield the names | |
76 | imported by that file. |
|
76 | imported by that file. | |
77 |
|
77 | |||
78 | >>> list(imported_modules( |
|
78 | Args: | |
|
79 | source: The python source to examine as a string. | |||
|
80 | ignore_nested: If true, import statements that do not start in | |||
|
81 | column zero will be ignored. | |||
|
82 | ||||
|
83 | Returns: | |||
|
84 | A list of module names imported by the given source. | |||
|
85 | ||||
|
86 | >>> sorted(imported_modules( | |||
79 | ... 'import foo ; from baz import bar; import foo.qux')) |
|
87 | ... 'import foo ; from baz import bar; import foo.qux')) | |
80 |
[' |
|
88 | ['baz.bar', 'foo', 'foo.qux'] | |
|
89 | >>> sorted(imported_modules( | |||
|
90 | ... '''import foo | |||
|
91 | ... def wat(): | |||
|
92 | ... import bar | |||
|
93 | ... ''', ignore_nested=True)) | |||
|
94 | ['foo'] | |||
81 | """ |
|
95 | """ | |
82 | for node in ast.walk(ast.parse(source)): |
|
96 | for node in ast.walk(ast.parse(source)): | |
|
97 | if ignore_nested and getattr(node, 'col_offset', 0) > 0: | |||
|
98 | continue | |||
83 | if isinstance(node, ast.Import): |
|
99 | if isinstance(node, ast.Import): | |
84 | for n in node.names: |
|
100 | for n in node.names: | |
85 | yield n.name |
|
101 | yield n.name | |
@@ -171,7 +187,8 def main(argv): | |||||
171 | f = open(source_path) |
|
187 | f = open(source_path) | |
172 | modname = dotted_name_of_path(source_path) |
|
188 | modname = dotted_name_of_path(source_path) | |
173 | src = f.read() |
|
189 | src = f.read() | |
174 |
used_imports[modname] = sorted( |
|
190 | used_imports[modname] = sorted( | |
|
191 | imported_modules(src, ignore_nested=True)) | |||
175 | for error in verify_stdlib_on_own_line(src): |
|
192 | for error in verify_stdlib_on_own_line(src): | |
176 | any_errors = True |
|
193 | any_errors = True | |
177 | print source_path, error |
|
194 | print source_path, error |
General Comments 0
You need to be logged in to leave comments.
Login now