eval to import a module

My little trick if you want to pass all the code as string to eval function:

>>> eval('exec("import uuid") or str(uuid.uuid4())')
'bc4b921a-98da-447d-be91-8fc1cebc2f90'
>>> eval('exec("import math") or math.sqrt(2)')
1.4142135623730951

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__.


Actually. if you absolutely need to import using eval (for example, code injection), you can do it as follow in Python 3, since exec is a function:

eval("exec('import whatever_you_want')")

For example:

enter image description here

Tags:

Python

Eval