Python is too dynamic to do this 100% correctly. Note that you can import modules by calling __import__ , which takes a string argument so that the name of the imported module can be built at run time. In addition, __import__ is a function, so it can be tied to other names, so you can’t even be sure to detect all cases when something is imported.
And it is technically possible for a module to call a function from another module that imports the module and returns it. Therefore, you definitely cannot do this by analyzing only package b .
And then there exec execute arbitrary python code built at runtime ...
Most likely, you can try and perform the unit test b exercise when a is on PYTHONPATH , and also when a not on PYTHONPATH . Still not reliable, as it only means that b completed all tests without a on PYTHONPATH , and not that he would never need a for anything. And if you're really unlucky, b does something really stupid and tinkers with sys.path in flight and somehow manages to import a .
If, however, this is all your own code, and you know that you aren’t doing this kind of stupid shit, then a simple script that scans files for import statements is probably your best bet. This probably worked very often on other people's random code. It is simply impossible to do the job perfectly with complete community.
source share