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>If you want to instantiate all the imported objects, you can access them through the global name space with <code>global()</code> built-in function.</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

instances = [obj() for name, obj in globals().items() if not name.startswith('__')]
</code></pre>

<p>Also note that basically creating all the instances at once is not a good idea, one reason is that you may don't want to use all of them all ways, and another one might be the problem with passing the specific arguments to constructors for each (or some) class, or if you have some imported objects that you don't want to instantiate, then have to take care of them too, and another problems as well.</p>

python dynamic constructor