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 <name>" 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

Try ...

names = [ "main", "secondary", "tertiary" ]
for item in names:
    cmd = "__import __(%s)" % item 
    eval( cmd )

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?

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
commented: good conclusion +4

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.