Python

How to Use Eval and Exec Functions in Python

This article will cover a guide on using “Eval” and “Exec” functions available in the standard python library. These functions can be used in a variety of ways to evaluate and execute Python expressions. The usage of both these functions can be best understood through examples. Some examples are listed below. All code samples in this article are tested with Python 3.9.5 on Ubuntu 21.04.

Using Eval to Evaluate Python Expressions

Eval function can be used to evaluate Python expressions and get a return value from them. Any Python expression that needs to be evaluated is supplied to the eval function in the form of a mandatory argument. Expressions passed as an argument to the Eval functions have full access to built-in Python functions as well as global and local namespaces. Have a look at the code sample below:

n = 1

result = eval('''n * 2''')

print (result)

eval('''print(n * 2)''')

Triple quotes in the example above are used to present strings “as is”, without escaping special characters or making any other modifications. The first statement in the code sample defines a variable called “n” having a value of 1. Next, the eval method is called by supplying it a Python expression in string format. In the string expression, variable “n” has been referenced as it is already available in the namespace. The next statement prints the output of the “result” variable. The last statement illustrates that you can directly call built-in Python functions in the expression supplied to the eval function as an argument.

After running the above code sample, you should get the following output:

2

2

As you can see in the output above, both print statements produce the same result.

You can optionally supply custom dictionaries for global and local namespaces to restrict and control allowed namespace objects. Have a look at the code sample below:

n = 1

result = eval('''n * 2''')

print (result)

eval('''print(m * 2)''', {'m': 1})

eval('''print(n * 2)''', {'m': 1})

In the eval statement in the fourth line, an extra argument is supplied where a dictionary of custom global namespace objects is used. When you supply a dictionary of custom global objects, only built-in methods and mappings included in the dictionary are used by eval. If you use an empty global dictionary (“{}”), only built-in methods are allowed and not even custom imports. Since the “m” object in the global dictionary has a value of 1, the eval statement is able to use a reference for “m”. In the last statement, “m” object is available in the global dictionary, but not the “n” variable, as a custom dictionary of global objects has been supplied. The last statement will throw an error as there is no definition for “n” in the custom global namespace dictionary.

After running the above code sample, you should get the following output:

2

2

Traceback (most recent call last):

 File "/home/user/Downloads/./test.py", line 7, in <module>

   eval('''print(n * 2)''', {'m': 1})

 File "<string>", line 1, in <module>

NameError: name 'n' is not defined

You can use a dictionary for local namespace objects in the same way as global namespace objects. Just supply a custom dictionary as a third argument for the eval function to use it as a mapping for local namespace objects.

Using Exec to Run Python Code

The exec function works similar to the eval function with some differences. The expression supplied to the exec function can be a string or any other valid Python object that contains valid Python code. In comparison, the eval function only takes string expressions. You can also supply custom dictionaries for both global and local namespace objects and the exec method behaves the same way as the eval function when custom namespace mappings are used. Another difference with eval function is that exec function always returns a “None” value. Have a look at the code sample below:

n = 1

result = exec('''n * 2''')

print (result)

exec('''print(n * 2)''')

result = '''print(n * 2)'''

exec(result)

The code block is very similar to the code sample used in the eval example, but instead of the eval function, now exec function has been used. After running the above code sample, you should get the following output:

None

2

2

As stated earlier, the exec function always returns a “None” value, so the third line produces “None” as the output. Next, the exec statement in the fourth line makes use of the “print” function to produce “2” as the output. The result variable is then assigned a new value by supplying it a valid Python code statement in string form. The last statement shows that the exec function can directly call upon code objects containing valid Python code. It also produces “2” as the output.

Security Considerations

While using eval and exec functions, you should be aware that both these functions allow executing of arbitrary Python expressions and code blocks. If you are not consciously aware about what is being used in expressions, these statements can do harm to the environment you are working in. For instance, you may be unintentionally modifying, removing or making irreversible changes to the files stored on the host by using the “os” and “sys” modules and their methods in eval and exec functions. The “subprocess” module in Python allows you to launch new processes and run shell commands. Expressions in eval and exec methods making use of the subprocess module can lead to unintended behaviors if you are not careful about what is being used in the expressions.

Conclusion

Both eval and exec methods allow you to process and execute Python code chunks. You can supply eval statements to other Python functions as arguments as they always return a value, somewhat similar to lambda functions in Python. Similarly, you can use the exec function to execute predefined Python code. It is most commonly used where Python code is needed to be read from one file and executed in another.

About the author

Nitesh Kumar

I am a freelancer software developer and content writer who loves Linux, open source software and the free software community.