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.