How do I dynamically create instances of all classes in a directory with python?
<p>I'm trying to do something like this:</p>

<pre><code>from A.AA import Q, W
from A.AB import E
from A.B.ABA import R
from A.B.ABB import T, Y, U

objs = []
objs.append(Q())
objs.append(W())
objs.append(E())
objs.append(R())
objs.append(T())
# and so on...
</code></pre>

<p>The above code is very large, and would take up a bunch of unnecessary time to update it every time I add a new class or module. Instead, I would like a way to dynamically initialize an object from each of the classes within a directory and all nested directories. Something that would abstract down to the following.</p>

<pre><code>objs = []
for py_file in directory:
    for class in py_file:
        objs.append(construct_object_of_type(class))
</code></pre>

<p>As a side note, all of those classes inherit from a single base class. This code would also be called from a python file in the top level directory.</p>

<p>So I managed to figure out how to do this.</p>

<p>Here's the code for it:</p>

<pre><code>import os
import imp
import inspect

obj_list = []

dir_path = os.path.dirname(os.path.realpath(__file__))
pattern = "*.py"

for path, subdirs, files in os.walk(dir_path):
    for name in files:
        if fnmatch(name, pattern):
            found_module = imp.find_module(name[:-3], [path])
            module = imp.load_module(name, found_module[0], found_module[1], found_module[2])
            for mem_name, obj in inspect.getmembers(module):
                if inspect.isclass(obj) and inspect.getmodule(obj) is module:
                    obj_list.append(obj())
</code></pre>

python dynamic constructor