Python Tutorial



Python Tutorial

Eval in Python

The eval() function in Python enables you to evaluate any Python expression given a string- or compiled-code-based input. This method is useful for evaluating Python expressions on-the-fly from any input that is provided as a string or an object of compiled code.

Despite being a very helpful tool, eval() in Python has some significant security consequences that you should take into account before using it. This tutorial will teach you how eval() serves and how to use it efficiently and securely in Python projects.


Python is a versatile programming language with a sizable function library that may simplify coding considerably. The Python eval() function is perhaps one of the most notable and widely used functions. In this post, we'll look in-depth at the Python eval vs exec method and explain how to utilize it.

What is the eval() function? 

A Python method called eval() is used to evaluate strings as Python expressions. It just requires one parameter, a string that refers to a Python expression. subsequently, this expression is evaluated by the eval() function, which subsequently returns the result. The Python eval() method analyzes the expression that is supplied to it before running the program's Python expression.

Python eval() Function Syntax 

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

Parameters: Strings are processed and evaluated like Python expressions.

globals [optional]:  Dictionary containing information about the accessible global methods and variables.

locals:  An optional dictionary that specifies the accessible local methods and variables.

Python eval() Function Example 

print(eval('11 + 2'))
print(eval("sum([1, 2, 3, 4])"))




Demonstration of eval() works

# A Simple Demonstration of eval() Function in Python

def function_creator():
    # Prompt the user to enter a mathematical expression in terms of 'x'
    expr = input("Enter the mathematical expression (in terms of x): ")

    # Prompt the user to enter a value for 'x'
    x = float(input("Enter the value of x: "))

        # Evaluate the expression using eval() and store the result in 'y'
        y = eval(expr)

        # Print the evaluated result
        print(f"Result of {expr} for x = {x}: y = {y}")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":


Enter the mathematical expression (in terms of x): x*(x 1)*(x 2)

Enter the value of x: 3

Result of x*(x 1)*(x 2) for x = 3.0: y = 60.0


  1. The function_creator function prompts the user to enter a python evaluate math expression without eval and a value for 'x.'

  2. It uses the eval() function to evaluate the provided expression with the given value of 'x.'

  3. The result is printed, showing the evaluated value of the expression for the specified 'x.'

Note: In the above example, we have  added error handling using a try-except block to catch potential exceptions that may occur during the evaluation, providing a more robust program. Additionally, we used float(input(...)) for 'x' input to allow for non-integer values.

Parameters of eval() in Python 

The eval() function in Python is used to evaluate a dynamically generated Python expression as a string. It takes three optional arguments:

  1. The expression argument (required):

  • This is a string representing the Python expression you want to evaluate. It can be a mathematical expression, a piece of Python code, or any valid Python expression.

  1. The globals argument (optional):

  • This argument is a dictionary that specifies the global symbols and variables available for the evaluation of the expression. It defines the global context for the evaluation. If not provided, it defaults to the current global symbol table (usually globals()).

  1. The locals argument (optional):

  • This argument is a dictionary that specifies the local symbols and variables available for the evaluation of the expression. It defines the local context for the evaluation. If not provided, it defaults to the current local symbol table (usually locals()).

Here are some examples to illustrate how eval() works with these arguments:

Example 1: Basic Expression evaluation in python with example

# Basic arithmetic expression
result = eval("3 4")
print(result)  # Output: 7 

In this example, we use eval() to evaluate the expression "3 4". Since we didn't provide globals or locals, the evaluation uses the current global and local symbol tables.

Example 2: Using globals and locals

# Define global and local variables
x = 5
y = 10
local_vars = {'x': 2, 'y': 3}

# Evaluate an expression with custom globals and locals
result = eval("x y", globals(), local_vars)
print(result)  # Output: 5 (uses local_vars for 'x' and 'y') 

In this example, we provide custom global and local dictionaries. The x and y variables inside the expression are resolved using the local_vars dictionary.

Example 3: Using globals to access built-in functions

# Using globals to access built-in functions
expression = "max(1, 5, 3)"
result = eval(expression, globals())
print(result)  # Output: 5 (maximum value among 1, 5, and 3) 

Here, we use globals to access the max function, which is a built-in Python function. The function is available in the global namespace.

Evaluating Expressions using Python’s eval() 

Basic Syntax:

result = eval(expression, globals=None, locals=None)
  • expression (required): A eval string python representing the expression or code you want to evaluate.

  • globals (optional): A dictionary specifying the global symbol table. It defines the global context for the evaluation. If not provided, it defaults to the current global symbol table (globals()).

  • locals (optional): A dictionary specifying the local symbol table. It defines the local context for the evaluation. If not provided, it defaults to the current local symbol table (locals()).

Simple Mathematical Expression:

result = eval("2 3")
print(result)  # Output: 5

Evaluate Boolean Expressions in Python

Because the value of x in this case is 6, which is not equal to 4, the eval expression x == 4 will evaluate to False. Because the value of x in the second eval expression is None and is None tests for object identity rather than value equality, it will evaluate to True.

x = 6
print(eval('x == 4'))

x = None
print(eval('x is None'))




Python evaluation of conditional expressions

On the Python eval() method, we may additionally assess conditional checks.

# check if element in tuple
chars = ('a', 'b', 'c')
print("'d' in chars tuple?", eval("'d' in chars"))

# check if number is greater or lesser
num = 100
print(num, "> 50?", eval('num > 50'))

# checking if number is even
num = 20
print(num, "is even?", eval('num % 2 == 0'))


'd' in chars tuple? False
100 > 50? True
20 is even? True

Vulnerability issues with Python eval() Function 

Here, we'll explain some common vulnerability issues associated with the eval() function and provide an example for each:

  1. Arbitrary Code Execution:

The most significant vulnerability with eval() is that it can execute arbitrary code. If you allow user input directly into an eval(input()) in python without proper sanitization and validation, it can lead to code execution vulnerabilities.

user_input = input("Enter a Python expression: ")
result = eval(user_input)

Example Scenario: If an attacker enters malicious code instead of a legitimate expression, it can lead to unintended consequences, such as deleting files, compromising the system, or executing any code they desire.

  1. Injection Attacks:

Just like SQL injection, using unsanitized user input within an eval() call can lead to code injection attacks. Attackers can inject malicious code to manipulate or exploit your application.

user_input = input("Enter a Python expression: ")
expression = f"result = {user_input}"

Example Scenario: An attacker enters os.system('rm -rf /') as input, and if it's evaluated by eval(), it can delete important files or even wipe the entire system.

  1. Access to Sensitive Data:

eval() can access global and local variables. If it's used carelessly, it may inadvertently expose sensitive data to an attacker.

user_input = input("Enter a Python expression: ")
result = eval(user_input, globals(), locals())

Example Scenario: If sensitive variables or functions are accessible through the global or local namespaces, an attacker can manipulate or extract this data by crafting a malicious input.

  1. Denial of Service (DoS):

Careless use of eval() can open the door to denial of service attacks. An attacker can create an expression that consumes excessive resources or goes into an infinite loop.

 user_input = input("Enter a Python expression: ")
 result = eval(user_input)

Example Scenario: An attacker enters an expression that contains an infinite loop (while True:), causing the program to hang indefinitely and consume CPU resources.

Making eval() safe 

Making the eval() function safe is a challenging task because of its inherent potential to execute arbitrary code. However, you can take certain precautions and follow best practices to minimize security risks when using eval(). Here are some strategies to make eval() safer, along with examples:

  1. Validate and Sanitize Input:

Always validate and sanitize input before passing it to eval(). Ensure that only trusted and well-formed expressions are evaluated.

user_input = input("Enter a mathematical expression: ")
# Validate and sanitize input
if all(c in "0123456789 -*/()" for c in user_input):
    result = eval(user_input)
    print("Invalid input.")

In this example, we check if the user input contains only valid mathematical expression characters before proceeding with eval().

  1. Limit Execution Context:

You can use custom global and local namespaces to limit the context in which eval() operates.

x = 5
y = 10
local_vars = {'x': x, 'y': y}

user_input = input("Enter an expression using x and y: ")

    result = eval(user_input, globals(), local_vars)
    print("Result:", result)
except NameError as e:
    print("Error:", e)

In this example, we define a limited set of variables in the local_vars dictionary, ensuring that eval() can only access those variables.

  1. Use a Function Wrapper:

Wrap the eval() call in a function to provide an additional layer of control and isolation.

def safe_eval(expression):
        result = eval(expression)
        return result
    except (SyntaxError, NameError, TypeError) as e:
        return f"Error: {e}"

user_input = input("Enter an expression: ")
result = safe_eval(user_input)

This way, you can catch and handle exceptions that may occur during evaluation and return informative error messages instead of crashing the program.

Uses of Python eval() Function 

Here are some common uses of the Python eval function with parameters:

  • Mathematical Expressions: Evaluate mathematical expressions dynamically.

  • Configuration Files: Parse and execute configuration files in Python scripts.

  • Interactive Calculators: Create interactive calculators or equation solvers.

  • Dynamic Code Generation: Generate and execute code on the fly.

  • Plugin Systems: Implement plugin systems where users can define and execute custom code.

  • Scripting: Execute user-provided scripts within a larger application.

  • Data Processing: Transform and manipulate data using user-defined expressions.

  • Formula Evaluation: Calculate results based on formulae provided by users.

  • Symbolic Mathematics: Perform symbolic mathematics for symbolic algebraic manipulation.

  • Unit Testing: Dynamically test code snippets and evaluate test cases.

  • Education: Create educational tools for teaching Python programming concepts.

  • Prototyping: Rapidly prototype code to test ideas and concepts.

  • Dynamic Behavior: Change the behavior of a program based on user input or conditions.

  • Experimentation: Allow users to experiment with code without modifying the source.

  • Expression Evaluation: Evaluate logical expressions for decision-making.

  • Code Templating: Generate code templates with placeholders to be filled by users.

  • Calculator Apps: Build calculator applications with custom functions.

Restricting The Use Of Built-Ins 

Restricting the use of built-in functions when using the eval() function is important for security and control, as allowing arbitrary built-in functions can pose a significant risk. You can achieve this by creating a safe evaluation environment that only exposes specific functions or variables. Here's how you can restrict the use of built-ins:

Use a Custom Namespace:

Create a custom namespace dictionary that only includes specific functions or variables that you want to expose during evaluation. This way, eval() can only access the symbols you provide.

allowed_globals = {'math': math}

user_input = input("Enter an expression: ")

    result = eval(user_input, allowed_globals)
    print("Result:", result)
except (NameError, SyntaxError) as e:
    print("Error:", e)

By controlling the allowed_globals dictionary, you limit the available functions and variables.


Python's eval() function is a wonderful tool that enables us to run dynamically generated code and carry out challenging mathematical operations. When using the eval() function, it is often recommended to exercise caution and be aware of any potential security, implementation, and maintenance concerns.


1. What is eval ()?

Evaluating or running an argument is what the eval() function does. Eval() evaluates an expression if the parameter is one. Eval() evaluates the arguments if they contain one or more JavaScript statements.

2. What are the eval's parameters?

Expression, globals, and locals are the three arguments required by the eval() method.

3. Is eval a keyword in python?

Yes, `eval` is a built-in function in Python, not a keyword. It is used to evaluate a string as a Python expression and return the result.

4. How to input list in python using eval?

You can input a list in Python using `eval` by providing a string representation of the list and then evaluating it. Here's an example:

my_list = eval(input("Enter a list: "))

This line of code prompts the user to enter a list as a string (for example, `"[1, 2, 3]"`) and then uses `eval` to convert it into an actual list.

Leave a Reply

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