1

Okay, so I'm trying to find a way to get a list of all modules in a package, into a variable.

My file structure is as such:

main/
  app.py
  __init__.py
  modules/
     __init.py
     mod_1.py
     mod2.py

All of the code is running from app.py . The modules folder will have many different modules in it, made by several people with a common interface. The goal is to have app.py import a list of all the modules in main.modules, and then iterate through them, doing calls such as:

for mod in module_list:
    mod.add(5,2)

I had a working version where I got a list of filenames, and then used module_list = map(__import__, file_list) to make a list of modules that I was able to loop through and call. The problem was, I was using the horrible method of sys.append('path/to/module/folder/') and filtering by .py extension to get my list of files, but the problem is that this wouldn't work well on other computers. Playing with the init.py files, I am able to now correctly import my main/ package from anywhere by simply:

import main

(with a better name obviously). And am able to do stuff such as:

main.modules.mod_1.add(5,2)

from main.modules import *
mod_1.add(5,2)
mod_2.add(6,2)

But I can't find a way to make a list of all of the modules in the main.modules 'package'

mods = main.modules.*
mods = from main.modules import *
import main.modules.* as mods

All don't work, and was the closest I could come. Any help would be great, thanks!

martineau
  • 119,623
  • 25
  • 170
  • 301
halolord01
  • 173
  • 1
  • 3
  • 8
  • [My answer](http://stackoverflow.com/a/5135444/355230) to the question [**_Importing classes from different files in a subdirectory_**](http://stackoverflow.com/questions/5134893/importing-classes-from-different-files-in-a-subdirectory) (and the link to yet another related question within it) might possibly be helpful to you. It's doing more than you need, but you can see how if finds the modules it imports. – martineau May 08 '17 at 21:51

0 Answers0