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?
Python eval() Function The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.
Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer.
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__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With