January 17th, 2005, 12:41 PM
Hello forum -
I'm fairly new to python, and the task I've set myself may be over my head, but let me describe what I want, and see if it makes sense...
I have my project structured something like this:
So - when I run my main.py, I would like it to load any 'derived_class' that is in the modules folder. I want to be able to just drop new class in that folder, and have them be added automatically.
So I've been playing with the os library, and I can get a list of the files in the modules folder. Then I can do some string manipulation, and the eval() function to load the class (provided the class has the same name as the file).
It seems rather sloppy though. I think I must be missing something. Do you have any suggestions on how to accomplish this more efficiently?
January 17th, 2005, 02:39 PM
I'm a little unsure on what your doing here, it seems like all you want is a package (a group of Python modules). In this case you can just do something like
from main.module.fileNameWithoutSuffix import className
assuming of course that the main folder is on Pythons search path; $PYTHONPATH/sys.path .
Hope this helps,
January 17th, 2005, 04:25 PM
This is a fairly common idiom. You can import a module dynamically using the built-in __import__ function. e.g.
for filename in glob.glob('path/to/modules/*.py'):
moduleName = os.path.splitext(os.path.basename(filename))
module = __import__(moduleName)
1) I use the glob module to get a list of all the *.py files. If you iterate over all the files in the directory then you will end up importing everything twice, since each .py file will also have a .pyc file with it.
2) I assume that each module has an initialise function that registers the module somewhere, so that my code can use it later on. However, what you do with the module once you have it loaded is up to you.
Dave - The Developers' Coach
Last edited by DevCoach; January 17th, 2005 at 04:28 PM.
January 17th, 2005, 06:04 PM
That's great, thanks for your help