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

Skip to content

Commit 9f93bf8

Browse files
committed
Python: Fix 'unused import' to no longer give alerts for imported modules used in doctests.
1 parent f147b63 commit 9f93bf8

4 files changed

Lines changed: 29 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
@@ -16,6 +16,7 @@
1616

1717
| **Query** | **Expected impact** | **Change** |
1818
|----------------------------|------------------------|------------------------------------------------------------------|
19+
| Unused import (`py/unused-import`) | Fewer false positive results | Results where the imported module is used in a doctest string are no longer reported |
1920

2021
## Changes to code extraction
2122

python/ql/src/Imports/UnusedImport.ql

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,22 @@ predicate all_not_understood(Module m) {
4141
)
4242
}
4343

44+
predicate imported_module_used_in_doctest(Import imp) {
45+
exists(string modname |
46+
((Name)imp.getAName().getAsname()).getId() = modname
47+
and
48+
/* Look for doctests containing the patterns:
49+
* >>> …name…
50+
* ... …name…
51+
*/
52+
exists(StrConst doc |
53+
doc.getEnclosingModule() = imp.getScope() and
54+
doc.isDocString() and
55+
doc.getText().regexpMatch("[\\s\\S]*(>>>|\\.\\.\\.).*" + modname + "[\\s\\S]*")
56+
)
57+
)
58+
}
59+
4460
predicate unused_import(Import imp, Variable name) {
4561
((Name)imp.getAName().getAsname()).getVariable() = name
4662
and
@@ -65,6 +81,8 @@ predicate unused_import(Import imp, Variable name) {
6581
and
6682
/* Assume that opaque `__all__` includes imported module */
6783
not all_not_understood(imp.getEnclosingModule())
84+
and
85+
not imported_module_used_in_doctest(imp)
6886
}
6987

7088

python/ql/src/semmle/python/strings.qll

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,4 @@ string repr(Expr e) {
5757
else
5858
result = e.toString()
5959
}
60+

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,12 @@ def __init__(self):
6161
#Use it
6262
different
6363

64+
import used_in_doctest
65+
66+
def f():
67+
'''
68+
>>> unrelated
69+
>>> used_in_doctest.thing() == f()
70+
True
71+
'''
72+
return 5

0 commit comments

Comments
 (0)