954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

eval() problems

Hi, I was wondering how to get around a problem I was having with eval(). I have a list of strings and each one is the name of a python file found in the same directory as the current script. I was it to import these modules to use in the current script, but: eval( "import" + modname ), where 'modname' is the script's name, causes an error. Is there any way to have the script import any found scripts or would I have to explicitly add "import " for each script? Thanks!

names = [ "main", "secondary", "tertiary" ]
for item in names:
    eval( "import " + item )

The code above makes sense, but python gives me this instead:

import primary
     ^
SyntaxError: invalid syntax
shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Try ...

names = [ "main", "secondary", "tertiary" ]
for item in names:
    cmd = "__import __(%s)" % item 
    eval( cmd )
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

I no longer got an error about the import function, but now, however, when I call a function from the "primary" module, it gives me an error saying:
NameError: name 'primary' is not defined.

So when I call function "draw()" from module "primary", it gives me the above error. Any ideas?

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Try and see this... I've been trying similar things after I read it and I had some trouble solving my bugs too... I needed the name of a class in a module in a package to be imported ...I still didn't get there but maybe your case is easier

http://technogeek.org/2007/05/29/dynamic-module-loading-in-python-2/

tzushky
Junior Poster in Training
96 posts since Jun 2008
Reputation Points: 10
Solved Threads: 5
 

Besides, that you do not have a "primary" module in the code...
Eval evaluates an expression in his own namespace and returns the result.
What you really want imho is to inject code.

Something like this:

for item in names:
    exec "import " + item
slate
Posting Whiz in Training
252 posts since Jun 2008
Reputation Points: 72
Solved Threads: 66
 

Oh awesome - I got it working using exec . I never knew that it existed... Thanks for solving my problem!

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You