Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 547b3eb

Browse files
committed
Python: Fix 'unused import' to no longer give alerts for imported modules used in typehints.
1 parent e82e779 commit 547b3eb

3 files changed

Lines changed: 24 additions & 0 deletions

File tree

change-notes/1.20/analysis-python.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
| **Query** | **Expected impact** | **Change** |
1818
|----------------------------|------------------------|------------------------------------------------------------------|
1919
| Unused import (`py/unused-import`) | Fewer false positive results | Results where the imported module is used in a `doctest` string are no longer reported. |
20+
| Unused import (`py/unused-import`) | Fewer false positive results | Results where the imported module is used in a type-hint comment are no longer reported. |
2021

2122
## Changes to code extraction
2223

python/ql/src/Imports/UnusedImport.ql

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,21 @@ predicate imported_module_used_in_doctest(Import imp) {
5757
)
5858
}
5959

60+
predicate imported_module_used_in_typehint(Import imp) {
61+
exists(string modname |
62+
((Name)imp.getAName().getAsname()).getId() = modname
63+
and
64+
/* Look for typehints containing the patterns:
65+
* # type: …name…
66+
*/
67+
exists(Comment tyephint |
68+
tyephint.getLocation().getFile() = imp.getScope().(Module).getFile() and
69+
tyephint.getText().regexpMatch("# type:.*" + modname + ".*")
70+
)
71+
)
72+
}
73+
74+
6075
predicate unused_import(Import imp, Variable name) {
6176
((Name)imp.getAName().getAsname()).getVariable() = name
6277
and
@@ -83,6 +98,8 @@ predicate unused_import(Import imp, Variable name) {
8398
not all_not_understood(imp.getEnclosingModule())
8499
and
85100
not imported_module_used_in_doctest(imp)
101+
and
102+
not imported_module_used_in_typehint(imp)
86103
}
87104

88105

python/ql/test/query-tests/Imports/unused/imports_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,9 @@ def f():
7070
True
7171
'''
7272
return 5
73+
74+
#Used in Python2 type hint
75+
import typing
76+
77+
foo = None # type: typing.Optional[int]
78+

0 commit comments

Comments
 (0)