Python eval() function

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

The eval() allows us to execute arbitrary strings as Python code. It accepts a source string and returns an object.

Its syntax is as follows:


Parameter          Description
expr(required) expr can be any valid Python expression
globals(optional) Global namespace to use while executing the source. It must be a dictionary. If not provided then the current global namespace will be used.
locals(optional) Local namespace to use while executing the source. It can be any mapping. If omitted, it defaults to globals dictionary.

If both globals and locals are omitted, the current global and local namespaces are used.

Here is an example demonstrating how eval() works:

The eval() is not just limited to simple expression. We can execute functions, call methods, reference variables and so on.

Note that the eval()  works only with an expression. Trying to pass a statement causes a SyntaxError .

You should never pass untrusted source to the eval() directly. As it is quite easy for the malicious user to wreak havoc on your system. For example, the following code can be used to delete all the files from the system.

The above code would fail if the os module is not available in your current global scope. But we can easily circumvent this by using the __import__() built-in function.

So is there any way to make eval() safe?

Specifying Namespaces

The eval() optionally accepts two mappings that serve as a global and local namespaces for the expression to be executed. If mapping(s) are not provided then the current values of global and local namespaces will be used.

Here are some examples:

Example 1:

Example 2:

Even though we have passed empty dictionaries as global and local namespaces, eval() still has access to built-ins (i.e __builtins__ ).

To remove built-ins from the global namespace pass a dictionary containing a key __builtins__  with the value None.

Example 3:

Even after removing the access to built-ins functions, eval() is still not safe. Consider the following listing.

This deceptively simple looking expression is enough to tank your CPU.

The key takeaway is that only use eval()  with the trusted source.

Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

Your email address will not be published. Required fields are marked *