alex2k8 alex2k8 - 3 months ago 42
Python Question

How to list imported modules?

How to enumerate all imported modules?

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

import os
import sys

import sys

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.