only import a module if we use something from it

This prevents a bogus line such as `from types import ` from being
generated.

surprisingly this was not detected as a problem until a change
in isort! Formerly it would remove the bad line, but now it (correctly!)
errors
This commit is contained in:
Jeff Epler 2022-12-13 16:00:24 -06:00
parent 5b9fefe4e5
commit 41beca14af
No known key found for this signature in database
GPG Key ID: D5BF15AB975AB4DE
1 changed files with 2 additions and 1 deletions

View File

@ -228,7 +228,8 @@ def convert_folder(top_level, stub_directory):
imports, type_imports = extract_imports(tree)
import_lines = ["from __future__ import annotations"]
for type_module, used_types in type_imports.items():
import_lines.append(f"from {type_module} import {', '.join(sorted(used_types))}")
if used_types:
import_lines.append(f"from {type_module} import {', '.join(sorted(used_types))}")
import_lines.extend(f"import {m}" for m in sorted(imports))
import_body = "\n".join(import_lines)
m = re.match(r'(\s*""".*?""")', stub_contents, flags=re.DOTALL)