Python: Fix 'unused import' to no longer give alerts for imported modules used in typehints.

This commit is contained in:
Mark Shannon
2019-01-22 17:38:09 +00:00
parent e82e7791fa
commit 547b3eb973
3 changed files with 24 additions and 0 deletions

View File

@@ -57,6 +57,21 @@ predicate imported_module_used_in_doctest(Import imp) {
)
}
predicate imported_module_used_in_typehint(Import imp) {
exists(string modname |
((Name)imp.getAName().getAsname()).getId() = modname
and
/* Look for typehints containing the patterns:
* # type: …name…
*/
exists(Comment tyephint |
tyephint.getLocation().getFile() = imp.getScope().(Module).getFile() and
tyephint.getText().regexpMatch("# type:.*" + modname + ".*")
)
)
}
predicate unused_import(Import imp, Variable name) {
((Name)imp.getAName().getAsname()).getVariable() = name
and
@@ -83,6 +98,8 @@ predicate unused_import(Import imp, Variable name) {
not all_not_understood(imp.getEnclosingModule())
and
not imported_module_used_in_doctest(imp)
and
not imported_module_used_in_typehint(imp)
}

View File

@@ -70,3 +70,9 @@ def f():
True
'''
return 5
#Used in Python2 type hint
import typing
foo = None # type: typing.Optional[int]