chila
chila

Reputation: 2442

List imported modules from an imported module in Python 3

I'd like to have a list of the names and files of imported modules form an imported module, like:

#!/usr/bin/python3

import importlib

module = importlib.import_module('someModule')

for mod in module.modules():
    print(mod.name)
    print(mod.file)

Upvotes: 2

Views: 223

Answers (2)

Sam Newbold
Sam Newbold

Reputation: 11

sys.modules is a dictionary of the imported modules, so

$ python
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> for name, mod in sys.modules.items():
...     print(name, mod.__name__, mod.__package__)
...
sys sys
builtins builtins
_frozen_importlib importlib._bootstrap importlib
_imp _imp
...

Upvotes: 0

J_H
J_H

Reputation: 20593

Python3 lets us pull in the module with exec(f'import {module_name}'), putting the result in globals()[module_name], or we can assign mod = importlib.import_module(module_name).

To see what other modules were directly pulled in by that, use:

def is_module(x):
    return str(type(x)) == "<class 'module'>"


def show_deps(mod):
    for name in dir(mod):
        val = getattr(mod, name)
        if is_module(val):
            print(name, val.__file__)

One could recurse through the tree to find transitive deps, if desired.

Upvotes: 2

Related Questions