Dynamic object import ??

Thomas Weholt thomas at gatsoft.no
Tue Feb 19 07:14:23 EST 2002

I got a dictionary :

objects = {}

that I want to be able to store object instances in and call with :

result = objects['name of object to use'].result(my_params)

The objects to use are stored in modules in a specific folder, say
Maybe the disk-structure could look like this :


Each module has a folder with name same as module and each module contains
an object called the same as the module, so Test1.py contains an object
called Test1, which has a method named result taking a specific set of

How can I dynamically import and create instances of the objects found in
the Test1, Test2, Test3 modules?
The result should be :

>>> print objects.keys()
>>> ['Test1','Test2','Test3']
>>> print objects['Test1'].result(my_params) # yields some result

I need a way to scan a given folder for modules, import the ones which fits
a certain criteria ( ie. has a proper config-file present etc.), create
instances and map this instance to the name of the module, all in a specific

Any clues appreciated.

NB! If possible, it would be great if the modules are imported in such a
manner that they're reloadable, using reload() in some way.

Best regards,
Thomas Weholt

More information about the Python-list mailing list