Dynamically loading python classes
exarkun at intarweb.us
Fri Apr 11 18:35:31 CEST 2003
On Fri, Apr 11, 2003 at 09:13:18AM -0700, Brian Bull wrote:
> I am writing an application that has to dynamically load classes from
> other modules based on certain criteria. I load the class initially
> like this:
> self.dict["handleUnknown"] =
> I later initialize this class by calling
> runningClass = self.dict[clas](self.pluginLog)
> where clas is the name of the class I want to load such as
> "handleUnknown" in this example
> I then execute methods against the class object and delete it when I
> am finished.
> What I am looking for is a way to load the class "fresh" each time I
> instantiate it. For instance, if I make a change to the loaded class,
> I want that change to be activated the next time the class is loaded
> without having to restart the main program that loads the classes.
The key here is probably to reload() the module you're getting the update
information from. This might be as easy as checking the last-modified
timestamp on the file it is loaded from in whatever routine you use to
> I also need to be able to load the module and class from strings
> instead of actually using the module/class name. ie.
> runningClass = handleUnknown.handleUnknown()
> This is what I want to be able to do (something similar to this)
> className = "handleUnknown"
> runningClass = className.className()
I'm not sure what the point of the above lines of code are, but from your
description it sounds like you will probably be interested in the
__import__() and getattr() builtin functions.
Examinations are formidable even to the best prepared, for
even the greatest fool may ask more the the wisest man can answer.
-- C.C. Colton
up 22 days, 13:01, 5 users, load average: 0.99, 0.98, 0.99
More information about the Python-list