Import class dynamically in Python
<p>I want to dynamically load a class from a given string. However, I do not know which file the class will be in, so I will have to search all files. I've tried this, but I get <code>AttributeError: 'module' object has no attribute 'MyClass'</code> even though I'm 100% sure that that module (in the current iteration) has that class:</p>

<pre><code>target = 'MyClass'
module_names = [mf[0:-3] for mf in os.listdir('application/models') if mf.endswith(".py")]
modules = [imp.new_module(x) for x in module_names]
for module in modules:
    try:
        target_class = getattr(module, target)
    except ImportError, AttributeError:
        continue

if target_class:
    print 'found class'
</code></pre>

<p>It seems I'm getting really close. What I want is not to limit the search to just one folder, but perhaps multiple folders. What's wrong with my code?</p>

<p>Edit: Ok now I'm trying something like this, but still getting the same error:</p>

<pre><code>    for m in module_names:
        try:
            x = reload(__import__(m))
            target_class = getattr(x, target)
        except ImportError, AttributeError:
            continue
        else:
            break

    if target_class:
        print 'found class'
</code></pre>
