eval to import a module
Asked Answered
A

4

44

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?

Agreement answered 16/6, 2013 at 19:13 Comment(0)
S
79

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

Samadhi answered 16/6, 2013 at 19:14 Comment(2)
A word of warning: exec is very powerful. If part of the string you are exec'ing comes from an untrusted source, then exec is also extremely dangerous.Galacto
With import for py <= 2.6, note that it doesn't leave the imported name defined, like a regular import would.Prindle
I
19

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:

>>> eval('exec("from math import *")')
>>> sqrt(2)
1.4142135623730951
Isothere answered 24/10, 2020 at 8:28 Comment(0)
O
9

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
Ossetic answered 15/1, 2021 at 15:30 Comment(0)
O
5

You can use __import__ inside of eval to import something.

eval("__import__('os').system('ls')")
Odey answered 6/1, 2023 at 1:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.