How do you dynamically load python classes from a given directory?

import, python

Solution

You are looking for `pkgutil.walk_packages`. Using this you can do the following:

def load(root_import_path, is_valid=lambda entity: True):
    """Returns modules in ``root_import_path`` that satisfy the ``is_valid`` test

    :param root_import_path: An string name for importing (i.e. "myapp").
    :param is_valid: A callable that takes a variable and returns ``True``
                     if it is of interest to us."""

    prefix = root_import_path + u"."
    modules = []

    for _, name, is_pkg in walk_packages(root_import_path, prefix=prefix):
        if is_pkg: 
            continue
        module_code = __import__(name)
        contents = dir(module_code)
        for thing in contents:
            if is_valid(thing):
                modules.append(thing)

    return modules

Alternatly, if you don't mind taking on a dependency, you could try the `straight.plugin` loader, which is a little more complicated than this simple `load` function.

Problem

If I define a module module with a corresponding directory of `module/`, can I dynamically load classes from children modules such as `a.py` or `b.py`? --module ----a.py ----b.py Does this require knowing the class name to search for? Could I setup a base class that will somehow load these children? The basic use case is to allow a user to write some code of his or her own that the program will load in. The same as how rails allows you to write your own controllers, views, and models in certain directories. The code for loading modules dynamically I have so far is ``` def load(folder): files = {} for filename in os.listdir(folder): if (filename[0] != '_' and filename[0] != '.'): files[filename.rstrip('.pyc')] = None # Append each module to the return list of modules modules = [] mod = __import__(folder, fromlist=files.keys()) for key in files.keys(): modules.append(getattr(mod, key)) return modules ``` I was hoping to modify it to return class objects.

Original source

Related problems