I am debugging a complex project with many nested dependencies and I need a way to see every single module that has been loaded into the current session. Is there a built-in function or a specific library that allows me to print a full list of imported modules at runtime, including sub-modules and third-party packages? I'm trying to identify potential version conflicts and redundant imports.
3 answers
The most direct way to achieve this is by using the built-in sys module. Specifically, sys.modules is a dictionary that maps module names to modules which have already been loaded. You can simply iterate through the keys of this dictionary to see everything currently in the namespace. To make it readable, you can use print(list(sys.modules.keys())). Keep in mind that this will show a lot of built-in and internal modules that Python loads by default. If you only want to see top-level packages or specifically third-party ones, you might need to filter the list by checking the __file__ attribute of each module to see where it is located on your disk.
Are you trying to do this for a simple script, or are you working within a virtual environment where you might also need to see the specific versions of these loaded modules?
You can use the pkg_resources or importlib.metadata libraries to get more detailed info, but for a quick list, pip freeze in the terminal is often easier.
I agree with Susan, but sys.modules is definitely better if you need the info from inside the execution flow. It gives you the "truth" of what the interpreter is actually seeing right at that moment.
I am working within a Virtualenv. Seeing the versions would actually be a huge help because I suspect that a sub-dependency is pulling in an older version of a library than what I have specified in my requirements file. If I can print the version alongside the module name, it would save me hours of manual checking across different site-packages folders.