How to list imported modules?


Question

How to enumerate all imported modules?

E.g. I would like to get ['os', 'sys'] for from this code

import os
import sys
1
129
2/1/2011 1:50:28 AM

Accepted Answer

import sys
sys.modules.keys()

An approximation of getting all imports for the current module only would be to inspect globals() for modules:

import types
def imports():
    for name, val in globals().items():
        if isinstance(val, types.ModuleType):
            yield val.__name__

This won't return local imports, or non-module imports like from x import y. Note that this returns val.__name__ so you get the original module name if you used import module as alias; yield name instead if you want the alias.

157
6/7/2017 12:41:57 AM

Find the intersection of sys.modules with globals:

import sys
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon