Dynamic object import ??

Thomas Weholt thomas at gatsoft.no
Tue Feb 19 13:14:23 CET 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
'dynamic_objects'.
Maybe the disk-structure could look like this :

/dev/test/dynamic_objects/Test1/Test1.py
/dev/test/dynamic_objects/Test1/__init__.py
/dev/test/dynamic_objects/Test2/Test2.py
/dev/test/dynamic_objects/Test2/__init__.py
/dev/test/dynamic_objects/Test3/Test3.py
/dev/test/dynamic_objects/Test3/__init__.py
/dev/test/dynamic_objects/__init__.py

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
parameters.

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
dictionary.

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