dynamic class/module use? (like Java's forName)

Alex Hunsley lard at tardis.ed.ac.molar.uk
Sun Jul 18 04:29:24 CEST 2004


Roy Smith wrote:
> In article <_OdKc.29430$v7.8250 at fe2.news.blueyonder.co.uk>,
>  Alex Hunsley <lard at tardis.ed.ac.molar.uk> wrote:
> 
> 
>>Does python provide a way to dynamically use modules and/or classes?
>>I'm thinking in the vein of Java's Class.forName.
> 
> 
> Just out of curiosity, why do you want to do that?
> 
> The google link you provided talked about eval and exec.  My experience 
> is that when I first started using Python (about 7 years ago), I used 
> eval and exec a lot.  Now, I can't remember the last time I ever wanted 
> to use either.
> 
> Can you give us an example of what you're trying to do?  My guess, 
> having not yet seen it, is that there's probably a better way to do it 
> than what you're asking.

Ok, the situation is that I am parsing a file that has "actions" (or 
commands) embedded in it. Different actions cause different things to 
happen to the file which is being preprocessed for something. Now, since 
I will have many actions, and want my python to be extensible so other 
users can add their own actions, rather than hard coding each action 
like so:

  if (actionString == "blah"):
      blahThang = blah(constructor stuff)
      blahThang.doSomething()
  else if (actionString == "blah2"):
      blahThang2 = blah2(constructor stuff)
      blahThang2.doSomething()
  else if (actionString == "blah3"):
      blahThang3 = blah3(constructor stuff)
      blahThang3.doSomething()
  else if (actionString == "blah2"):
   # etc etc

... I can have a different python class (and hence source file) for each 
action, and the code for launching an action becomes generic (i.e. 
creates instance of the class based on the command string and calls 
agreed methods on it). I prefer this to the altyernative of hardcoding 
each action with an 'if', as above, and then getting another user who 
wants to extend my project have to add yet another if clause as well as 
some code.
Another advantage of this generic approach is that it encourages other 
users extending my code to put actions in seperate files, one per 
action, rather than adding 'magic' code into the above 'if' chaos.

Basically, modular actions is the idea!

I'd be keen to hear peoples thoughts on my approach.

thanks
alex









More information about the Python-list mailing list