Connor
Connor

Reputation: 698

How to iterate through a list of modules and call their methods in Python 3

Goal: Ability to drop files into "modules" folder & call a common set of methods/vars from each file.

Should the modules be initialized as static classes if all of the modules have common methods/vars?

My project folder tree:

/client
    __init__.py

    /modules
        __init__.py
        foo.py
        bar.py
        spam.py

client __init__.py file:

from client.modules import __all__ as moduleStrings

(get list of "modules" from "moduleStrings") # How do I write this function?

# Initialize modules dynamically
for module in modules:
    if (hasattr(module, 'init')):
        print(module.__name__)
        print("Has an initialize method!")
        module.init()

# Call the do_stuff method in each module
for module in modules:
    if (hasattr(module, 'do_stuff')):
        print("Has a do_stuff method!")
        module.do_stuff()

modules __init__.py file:

# Stores a list of module string names in __all__
import os
import glob
files = glob.glob(os.path.dirname(__file__)+"/*.py")
__all__ = [ os.path.basename(f)[:-3] for f in files if "__init__" not in f]

Upvotes: 4

Views: 7349

Answers (1)

A. STEFANI
A. STEFANI

Reputation: 6736

You may use the native python "imp" module (https://docs.python.org/3.4/library/imp.html):

Assuming the same project tree:

/client
__init__.py

/modules
    __init__.py
    foo.py
    bar.py
    spam.py

client init.py file:

# -*- coding: utf-8 -*-
#!/usr/bin/python

import modules.__init__
#here you generate
modules.__init__.__load_all__()

modules init.py file:

# -*- coding: utf-8 -*-
#!/usr/bin/python

import imp,os

def __load_all__(dir="modules"):
    list_modules=os.listdir(dir)
    list_modules.remove('__init__.py')
    for module_name in list_modules:
        if module_name.split('.')[-1]=='py':
            print "Load module ' ",module_name,"' :"
            foo = imp.load_source('module', dir+os.sep+module_name)
            foo.MyClass()

and finally

modules (spam.py,bar.py, foo.py, etc...) file:

# -*- coding: utf-8 -*-
#!/usr/bin/python

def __init__():
    print "load"

def MyClass():
    print "myclass spam,bar,foo, etc..."

When running client __init__.py, we iterate through the modules and initialize them dynamically.

Upvotes: 4

Related Questions