[Tutor] Importing and creation on the fly

Kent Johnson kent37 at tds.net
Tue Jun 26 19:18:34 CEST 2007


Tino Dai wrote:
> Hi there,
> 
>      I've been banging my head on this for about two weeks, and I can't 
> figure out a solution to this. I'm wondering if you could assist me on 
> this pesky problem.
> 
>      I'm reading in an xml file that has the name of class, location, 
> and the filename into a dictionary. I want to import these classes and 
> create instances of them.  The code in question is as follows:
> 
>  36       for xmlKey in self.dictXML.keys():
>  37             if not self.dictXML[xmlKey]['location'] in sys.path and \
>  38             not self.dictXML[xmlKey]['location'] == os.getcwd():
>  39                 sys.path.append(self.dictXML[xmlKey]['location'])
>  40             try:
>  41                 if os.stat(self.dictXML[xmlKey]['location'] + \
>  42                 self.dictXML[xmlKey]['filename']):
>  43                     eval('import ' + 
> self.dictXML[xmlKey]["class"])   <-- syntax error here
>  44                     actionStmt=self.dictXML[xmlKey]["class"] + '.' + 
> self.dictXML [xmlKey]["class"] + '()' 45                    
> 45                          self.objList.append(eval(actionStmt))
> 46             except:
>  47                 pass
> 
> 
> I have also tried: __import__( self.dictXML[xmlKey]["class"]), which 
> gave me an error when I did the eval(actionStmt). Could anybody shed 
> some light on this? Thanks in advance.

eval() won't work because it evaluates expressions; import is a 
statement, not an expression. You might have better luck with exec for 
the import.

__import__() doesn't put the imported module into the global namespace 
the way an import statement does; it returns a reference to the module 
which you assign to a name. So I think you would need something like
module = __import__(self.dictXML[xmlKey]["class"])
obj = getattr(module, self.dictXML[xmlKey]["class"])()

Kent


More information about the Tutor mailing list