eval to import a module

Siddharth picture Siddharth · Jun 16, 2013 · Viewed 22.1k times · Source

I can't import a module using the eval() function.

So, I have a function where if I do import vfs_tests as v it works. However, the same import using eval() like eval('import vfs_tests as v') throws a syntax error.

Why is this so?

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · Jun 16, 2013

Use exec:

exec 'import vfs_tests as v'

eval works only on expressions, import is a statement.

exec is a function in Python 3 : exec('import vfs_tests as v')

To import a module using a string you should use importlib module:

import importlib
mod = importlib.import_module('vfs_tests')

In Python 2.6 and earlier use __import__.