[Tutor] Importing and creation on the fly
Tino Dai
tinoloc at gmail.com
Tue Jun 26 20:18:34 CEST 2007
On 6/26/07, Dave Kuhlman <dkuhlman at rexx.com> wrote:
>
> On Tue, Jun 26, 2007 at 12:20:18PM -0400, 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.
>
> For the task of importing, look at the "imp" module:
>
> http://docs.python.org/lib/module-imp.html
>
> Also, the "inspect" module may be of help:
>
> http://docs.python.org/lib/module-inspect.html
>
> In particular, look at the the inspect.getmembers() and
> inspect.isclass() methods.
>
> Dave
Thanks guys. I will look into that this afternoon
-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070626/372c24d8/attachment.htm
More information about the Tutor
mailing list