Python eval Function – Examples & Uses

Free Python course with 25 real-time projects Start Now!!

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

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.

1. 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?

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

Python eval Example

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

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

Output

49

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.

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

Output

3

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")')

Output

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

Getting the Expression From the User in Python

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')

Output

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

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

Output

Enter the value of x2

>>> eval(expr)

Output

40

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.

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

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

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

Output

Enter an expression as xlet_me_in()

>>> eval(expr)

Output

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.

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

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():
        password='@dc#431'
        print("The password is",password)
>>> expr=input('Enter an expression as x')

Output

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

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

Output

Enter the value of x2

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

Output

40

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

Output

Enter an expression as xlet_me_in()

>>> eval(expr,safe_dict)

Output

Traceback (most recent call last):
File “<pyshell#56>”, line 1, in <module>
eval(expr,safe_dict)
File “<string>”, line 1, in <module>
NameError: name ‘let_me_in’ is not defined

Works fine.
Now, let’s talk about the uses of eval.

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.

A Final Python eval Example

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

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

Output

What would you like to do?triple

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

Output

What number?7

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

Output

21

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.

Python Interview Questions on eval function

  1. What is Python eval function? Explain with example.
  2. What does eval() do in Python?
  3. Explain the difference between eval and int in Python?
  4. What does eval mean in Python?
  5. How do you use eval in Python?

Conclusion

Hence, we discussed the Python eval() function and how and where to use it. Moreover, we saw vulnerability and uses of Python eval with examples.

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

  3. Aishwarya Kashyup says:

    #avoiding the exploitation of eval function
    def let_me_in():
    password = ‘abcd@1234’
    print(“The password is : “, password)

    safe_dict = {}
    safe_dict[‘x’] = x

    expr = input(“Enter the value of x: “)
    eval(expr,safe_dict) = > We get error
    #avoiding the exploitation of eval function
    def let_me_in():
    password = ‘abcd@1234’
    print(“The password is : “, password)

    safe_dict = {}
    safe_dict[‘x’] = x

    expr = input(“Enter the value of x: “)
    eval(expr,safe_dict) => Here we get error
    #avoiding the exploitation of eval function
    def let_me_in():
    password = ‘abcd@1234’
    print(“The password is : “, password)

    safe_dict = {}
    safe_dict[‘x’] = x

    expr = input(“Enter the value of x: “)
    eval(expr,safe_dict)=> If we remove safe_dict and evaluate the function we still get the password. So how is it safe?

  4. Chanchal Das says:

    I have also same question

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.