Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eval to import a module

Tags:

python

eval

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?

like image 837
Siddharth Avatar asked Jun 16 '13 19:06

Siddharth


People also ask

What does eval () do in Python?

Python eval() Function The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.

What is __ import __ in Python?

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

What is eval in tkinter?

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.


1 Answers

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

like image 63
Ashwini Chaudhary Avatar answered Oct 09 '22 22:10

Ashwini Chaudhary