Python Forum

Full Version: finding which source files import a module
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i would like to know of a script that can be given the name of a particular module to look for and the path names of a bunch of Python source files (some do not have ".py" at the end), and it will determine while files, when run as Python, could import that module, or from that module, import parts of it. it would not need to check flow of control conditions, though it could be helpful if some of the more obvious are checked, such as in if False: and such. but it does need to handle the variety of ways to code doing an import and parse all the names involved.
Aren't you looking for importlib.util.find_spec()?
i don't think so. i want to scan through a bunch of python source file to check which ones apparently import (something from) a named module which is one of my modules, usually. i have been using grep but it matches on other lines. i want to match only on the various import lines but in a case of "from foo import bar" and i am looking for a module named "bar" then this is not a match. likewise "import foo as bar" is not a match.
You may find existing tools for this. There is a module modulefinder in the standard library. There is a module named modulegraph in pypi. There are probably other such tools to look for. See these awesome graphs built with the help of the modulegraph module! The code is here