dacefa
dacefa

Reputation: 51

Python list all submodules imported from module

My code starts with the following:

from module import *

How can I get a list of all submodules imported from this module.

For example module has:

module.submodule
module.submodule2
module.anothersubmodule

I want to get after from module import *:

[submodule, submodule2, anothersubmodule]

(not strings with name of submodules, but a list with all submodules themselves)

UPD: I understood that I asked about XY problem. So here's what i'm trying to achieve: I have a folder called modules that will have a bunch of scripts following the same pattern. They will all have a function like main(). In my main script i want to import them all and iterate like that:

for i in modules:
    i.main(*some_args)

Upvotes: 5

Views: 5688

Answers (2)

Arount
Arount

Reputation: 10431

What about importlib?

import importlib
import os

directory = './module'

for filename in os.listdir(directory):
    filepath = os.path.join(directory, filename)
    if not os.path.isfile(filepath):
        continue

    modulename = os.path.splitext(filename)[0]

    args = [filename, filepath]

    module = importlib.import_module('module.{}'.format(modulename))
    module.main(*args)

With 3 differents Python files in ./modules, all like:

def main(*args):
    print('module one: {}'.format(', '.join(args)))

It gives:

module three: three.py, ./module/three.py
module two: two.py, ./module/two.py
module one: one.py, ./module/one.py

Upvotes: 3

Jon
Jon

Reputation: 431

Use the pkgutil module. For example:

import pkgutil
import module

modualList = []
for importer, modname, ispkg in pkgutil.iter_modules(module.__path__):
    modualList.append(modname)

Upvotes: 13

Related Questions