Reload all modules in a directory
Question: I need to reload all the python modules within a specified directory.

I've tried something like this:

    
    
    import sys, os
    import_folder = "C:\\myFolder"
    sys.path.insert( 0 , import_folder )
    for dir in os.listdir(import_folder):
        name = os.path.splitext(dir)[0]
        ext = os.path.splitext(dir)[1]
        if ext == ".py":
            import( eval(name) )
            reload( eval(name) )
    

Anyone know how to do this correctly?


Answer: 
    import os # we use os.path.join, os.path.basename
    import sys # we use sys.path
    import glob # we use glob.glob
    import importlib # we use importlib.import_module
    
    import_folder = 'C:\\myFolder'
    sys.path.append(import_folder) # this tells python to look in `import_folder` for imports
    for src_file in glob.glob(os.path.join(import_folder, '*.py')):
    name = os.path.basename(src_file)[:-3]
    importlib.import_module(name)
    reload(sys.modules[name])
    importlib.import_module(name)
    

There is the code. Now to the semantics of the whole thing: using
[importlib](http://docs.python.org/2/library/importlib.html#importlib.import_module)
makes this a little bit more normal, but it still promotes some bugs. You can
see that this breaks for source files in a subdirectory. What you should
probably do is: import the package, (import the whole folder), and use the `.`
operator like so:

    
    
    import sys # we use sys.path
    sys.path.append('C:\\')
    import myFolder
    ...
    myFolder.func1(foo)
    myFolder.val
    bar = myFolder.Class1()
    

Perhaps you should take a look at the [documentation for
modules](http://docs.python.org/2/tutorial/modules.html#packages), but don't
forget to update the path to include the parent of the folder you want to
import.

