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

Dani AI

Generated

Short diagnosis: import is a statement (not an expression), so eval(...) raises a SyntaxError. exec can run statements (which is why 's suggestion worked for ), but exec/eval are brittle and unsafe for dynamic loading. Prefer the standard import APIs for clarity and maintainability.

A concise, modern approach is importlib.import_module() and keeping imported modules in a mapping rather than injecting names into globals:

import importlib

loaded = {}
for name in names:
    loaded[name] = importlib.import_module(name)

# call a function from the module
loaded['primary'].draw()

If you only have file paths (not importable package names), use the importlib utilities to load a module from a filename:

import importlib.util, sys

spec = importlib.util.spec_from_file_location('mymod', '/path/to/mymod.py')
mymod = importlib.util.module_from_spec(spec)
sys.modules['mymod'] = mymod
spec.loader.exec_module(mymod)

If you need to support older code or dotted names, __import__() can be used correctly (remember the fromlist argument to get submodules), but importlib.import_module() handles dotted names more cleanly.

Troubleshooting / best practices:

  • Ensure the directory containing the modules is on sys.path, or use the file-based loader above.
  • Avoid exec/eval for imports — they hide errors and are a security risk. Importing a module runs its top-level code, so never import untrusted files.
  • For plugin systems prefer a clear API: detect modules with pkgutil.iter_modules() or declare plugins via packaging entry points, then import and validate a known function/class.
  • During development use importlib.reload() to refresh a module when needed.

This complements , and : use the standard import machinery for predictability and safety rather than string-evaluated statements.

Recommended Answers

All 5 Replies

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?

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

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.