Skip to content

Commit 220f227

Browse files
committed
Python: Add wrapper for isPreferredModuleForName
We talked about how it's annoying that we in 4 places have the same fix `isPreferredModuleForName(<module>.getFile(), <name> + ["", ".__init__"])` , and that it would be nice to have a simple wrapper predicate that ensures we never forget to do the `+ ["", ".__init__"]` dance... I had trouble coming up with a name for this (ironically), but I think `getModuleFromName` is good enough.
1 parent 66c3529 commit 220f227

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

python/ql/lib/semmle/python/dataflow/new/internal/ImportResolution.qll

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,22 @@ module ImportResolution {
167167
)
168168
}
169169

170+
/**
171+
* Gets the (most likely) module for the name `name`, if any.
172+
*
173+
* Handles the fact that for the name `<pkg>` representing a package the actual module
174+
* is `<pkg>.__init__`.
175+
*
176+
* See `isPreferredModuleForName` for more details on what "most likely" module means.
177+
*/
178+
pragma[inline]
179+
private Module getModuleFromName(string name) {
180+
isPreferredModuleForName(result.getFile(), name + ["", ".__init__"])
181+
}
182+
170183
/** Gets the module from which attributes are imported by `i`. */
171184
Module getModuleImportedByImportStar(ImportStar i) {
172-
isPreferredModuleForName(result.getFile(), i.getImportedModuleName() + ["", ".__init__"])
185+
result = getModuleFromName(i.getImportedModuleName())
173186
}
174187

175188
/**
@@ -224,7 +237,7 @@ module ImportResolution {
224237
exists(string module_name | result = getReferenceToModuleName(module_name) |
225238
// Depending on whether the referenced module is a package or not, we may need to add a
226239
// trailing `.__init__` to the module name.
227-
isPreferredModuleForName(m.getFile(), module_name + ["", ".__init__"])
240+
m = getModuleFromName(module_name)
228241
or
229242
// Module defined via `sys.modules`
230243
m = sys_modules_module_with_name(module_name)
@@ -235,7 +248,7 @@ module ImportResolution {
235248
ar.accesses(getModuleReference(p), attr_name) and
236249
result = ar
237250
|
238-
isPreferredModuleForName(m.getFile(), p.getPackageName() + "." + attr_name + ["", ".__init__"])
251+
m = getModuleFromName(p.getPackageName() + "." + attr_name)
239252
)
240253
or
241254
// This is also true for attributes that come from reexports.
@@ -249,8 +262,7 @@ module ImportResolution {
249262
exists(string submodule, Module package |
250263
SsaSource::init_module_submodule_defn(result.asVar().getSourceVariable(),
251264
package.getEntryNode()) and
252-
isPreferredModuleForName(m.getFile(),
253-
package.getPackageName() + "." + submodule + ["", ".__init__"])
265+
m = getModuleFromName(package.getPackageName() + "." + submodule)
254266
)
255267
}
256268

0 commit comments

Comments
 (0)