I want to access some kind of import dependency tracking in Python, if there is any.
I decided to add to my module a __dependencies__
dict describing versions of all modules imported by the module.
I want to have an automated way of obtaining a list of modules imported by my module. Preferably in the last line of the module.
ModuleFinder
(as suggested by How to list imports within a Python module? ) would not work since the inspection shall be performed for already loaded module.
Another problem with ModuleFinder
is that it inspects a Python script (with if __name__ == '__main__'
branch), not a module.
If we consider a toy script script.py:
if __name__ == '__main__':
import foo
then the result is:
>>> mf = ModuleFinder
>>> mf.run_script('script.py')
>>> 'foo' in mf.modules
True
which should be False if script is imported as a module.
I do not want to list all imported modules - only modules imported by my module - so sys.modules
(suggested by What is the best way of listing all imported modules in python?) would return too much.
I may compare snapshots of sys.modules
from the beginning and the end of the module code. But that way I would miss all modules used by my module, but imported before by any other module.
It is important to list also modules from which the module imports objects.
If we consider a toy module example.py:
from foo import bar
import baz
then the result should be like:
>>> import example
>>> moduleImports(example)
{'foo': <module 'foo' from ... >,
'baz': <module 'baz' from ...>}
(it may contain also modules imported recursively or foo.bar
given bar is a module).
Use of globls()
(according to How to list imported modules?) requires me to deal with non-module imports manually, like:
from foo import bar
import bar
How can I avoid that?
There is another issue with my solution so far. PyCharm tends to clean up my manual imports on refactoring, which makes it hard to keep it working.