Python eval Function – Examples & Uses

Keeping you updated with latest technology trends, Join DataFlair on Telegram

1. Objective – Python eval Function

Today, in this Python tutorial, we will see Python eval function. Moreover, we will understand the eval function in Python with examples. Also, we will look at uses and vulnerabilities in eval().

So, let’s start the Python eval tutorial.

Python eval Function

Python eval Function – Examples & Uses

2. What is Python eval Function?

eval() in Python is a built-in function or method, to which we pass an expression. It parses this expression and runs it as we execute the program. Let’s take a look at the syntax first.

a. The syntax of Python eval() Function

Observe the following syntax for eval function in Python:

eval(expression, globals=None, locals=None)

What does this tell us about Python eval()? What are the parameters of Python eval Function?

Before going on you must read the facts about Python Functions

b. Python eval Function with Parameters

  • Expression in Python eval()- This is the string to parse and evaluate
  • Globals in eval()- This is a dictionary that holds available global methods and variables, and is an optional parameter
  • Python eval Locals- This is a mapping object that holds available local methods and variables, and is an optional parameter. We know that the standard mapping type in Python is a dictionary.

3. Python eval Example

Let’s take a simple example of Python eval() Function.

>>> x=7
>>> eval('x**2')


In this eval function in Python example, we initialize x to 7. We then pass a string to eval that, we expect, will square the value of x and stuff it into x. We see that it works fine. eval in Python evaluates the expression x**2 to get to the value 49 and then prints it.
Now, let’s try another Python eval() example.

Have a look at Python Variables

>>> eval('[2,3,4][1]')

This converts the string to the list [2,3,4] and returns the value at position 1, that is, 3.

However, eval() in Python does not compile, only evaluates:

>>> eval('if 3>1: print("Okay")')

Traceback (most recent call last):
File “<pyshell#59>”, line 1, in <module>
eval(‘if 3>1: print(“Okay”)’)
File “<string>”, line 1
if 3>1: print(“Okay”)
SyntaxError: invalid syntax

4. Getting the Expression From the User

In the examples so far, we hardcoded the expression. What if we wanted to let the user provide one instead?

>>> expr=input('Enter an expression as x')

Enter an expression as x3*x**3+2*x**2+x+6

>>> x=int(input('Enter the value of x'))

Enter the value of x2

Do you know about Python Syntax

>>> eval(expr)


Here, we take the expression from the user, then we take the value of x and convert it to an integer. Finally, we call eval() on the expression and evaluate it to reach a value of 40.

5. Vulnerabilities With Eval in Python

So this is useful, but it can also be used against us since it executes anything we pass to it(somewhat like SQL injection). Let’s see how. The user can:

  • Call a dangerous function
  • Expose hidden values
Python eval Function

Vulnerabilities With Python eval Function

a. Exploiting Eval in Python

Imagine having a function in your code that returns some kind of password or other confidential data. A user can make a call to this function through Python eval() and make their way to the piece of sensitive data.

Clear your concepts for errors and exceptions in Python

>>> def let_me_in():
         print("The password is",password)
>>> expr=input('Enter an expression as x')

Enter an expression as xlet_me_in()

>>> eval(expr)

The password is @dc#431

Did you see how easy it was to extract the password from the code? All it took was one call to a function.

b. Protecting Python Eval from exploitation

Now consider you have imported the os module for some reason. How would you like a user to be able to read and write your files, or worse, delete them? This is possible using the command os.system(‘rm -rf *’). This could pose higher risks when working with applications like web apps and kiosk computers.

Have a look at Python Lists with the example

So what do we do? Well, for one, it is possible to pass a list of functions and variables to eval. This means it can access only these functions and variables. We pass this as a Python eval dictionary. Confused? Take a look:

>>> def let_me_in():
        print("The password is",password)
>>> expr=input('Enter an expression as x')

Enter an expression as x3*x**3+2*x**2+x+6

>>> x=int(input('Enter the value of x'))

Enter the value of x2

>>> safe_dict={}
>>> safe_dict['x']=x
>>> eval(expr,safe_dict)


>>> expr=input('Enter an expression as x')

Enter an expression as xlet_me_in()

>>> eval(expr,safe_dict)

Traceback (most recent call last):
File “<pyshell#56>”, line 1, in <module>
File “<string>”, line 1, in <module>
NameError: name ‘let_me_in’ is not defined
Do you know about Python Operators
Works fine. Now, let’s talk about the uses of eval.

6. Uses of eval in Python

While used sparingly because of its vulnerabilities, Python eval() manages to find use in some situations-

  • To allow users to enter own scriptlets to allow customization of a complex system’s behavior.
  • To evaluate mathematical expressions in applications instead of writing an expression parser.

7. A Final Python eval Example

So before we leave, let’s take a rather practical example of Python eval() Function.

Python Interview Questions

Let’s take a tour of Python Iterator

>>> def double(n):
        return n*2
>>> def triple(n):
        return n*3
>>> choice=input('What would you like to do?')

What would you like to do?triple

>>> num=input('What number?')

What number?7

>>> choice+='('+num+')'
>>> eval(choice)

Here, we provide the user with a choice- to double or triple a number of her/his choice. We use eval to make this happen.

So, this was all in Python eval Function Tutorial. Hope you like our explanation.

8. Conclusion – Python eval Function

Hence, we discussed the Python eval() function and how and where to use it. Moreover, we saw vulnerability and uses of Python eval. Also, we understand Python eval() Function with the examples. Next, we will talk about exec(). Still, if you have any confusion, comment below. We will definitely get back to you.
See also – 
Python Assert Statements
Python Interview Questions
For reference

3 Responses

  1. sandeep says:

    good content !!. bit more explanation for final eval example required. I did not understand how did we get 21 there.

  2. Chandan Kumar Manna says:

    I have some doubt sir , how we get the password from the eval(expr)

    • DataFlair Team says:

      Hi Chandan,

      Your program has a function that exposes sensitive information like a password. The user won’t get access to the code as users will only interact with the gui of our application. If we have an eval expression in the input of our gui then any user can use that function name to get the sensitive information that is available only to developers, so that is why eval should be used carefully, only when it is needed.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.