Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Difference between != and is not operator in Python
Next article icon

Difference Between eval() and ast.literal_eval() in Python

Last Updated : 04 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python provides multiple ways to evaluate expressions and convert data from one format to another. Two commonly used methods are eval() and ast.literal_eval(). While they might appear similar, they serve very different purposes and have significant security implications. This article explores the key differences between eval() and ast.literal_eval(), their use cases, security concerns and best practices.

Table of Content

  • What is eval()?
  • what is ast.literal_eval?
  • Key difference between eval() and ast.literal_eval
  • When to Use eval() and ast.literal_eval()
  • Security Implications and best Practices

What is eval()?

eval() is a built-in Python function that parses and evaluates expressions passed as a string. It can handle a wide variety of inputs, including arithmetic expressions, function calls, and even arbitrary code execution.

Syntax of eval()

eval(expression, globals=None, locals=None)
  • expression: A string representing the Python expression to evaluate.
  • globals: A dictionary representing the global namespace.
  • locals: A dictionary representing the local namespace.

Example:

Python
exp = "2 + 3" # expression  res = eval(exp) print(res) 

Output
5 

Explanation: In this example, eval() evaluates the string "2 + 3" and returns the result 5.

Key Features of eval()

  • Powerful: It can evaluate any valid Python expression, including arithmetic operations, list comprehensions, function calls, and more.
  • Dynamic Execution: eval() allows execution of Python code dynamically at runtime.
  • Flexible: It can execute complex code beyond simple expressions, including conditionals, loops, and even function definitions.
  • Security Risk: Since eval() can execute arbitrary code, it poses serious security vulnerabilities if used with untrusted input.

What is ast.literal_eval?

ast.literal_eval() is a function from Python's ast (Abstract Syntax Tree) module. It safely evaluates a string containing a Python literal or a container object. Unlike eval(), it only processes basic literals like strings, numbers, lists, tuples, dictionaries, booleans, and None. It raises an error if the input contains anything beyond these, making it significantly safer.

Syntax of ast.literal_eval()

import ast
ast.literal_eval(node_or_string)
  • node_or_string: A string containing a Python literal to be evaluated.

What is Abstract Syntax Tree (AST)?

The Abstract Syntax Tree (AST) is a representation of source code structure. It breaks down the syntax into a tree-like format where each node represents a component of the syntax. The ast module provides access to Python’s AST and literal_eval() ensures that only safe literals are evaluated. Example:

Python
import ast  # Converting a string representation of a list to an actual list s = "[1, 2, 3, 4]" res = ast.literal_eval(s) print(res) 

Output
[1, 2, 3, 4] 

Explanation: In this example, ast.literal_eval() converts the string representation of a list into an actual list.

How does ast.literal_eval() work?

ast.literal_eval() parses the string into an AST syntax tree and verifies that it contains only valid literals. If an unsafe operation (such as function calls or execution commands) is found, it raises an exception. Example:

Python
import ast  # Safe string evaluation safe_expression = '{"name": "Aditya", "age": 24}' res = ast.literal_eval(safe_expression) print(res)  # Unsafe expression (raises ValueError) unsafe_expression = "os.system('rm -rf /')"  try:     res = ast.literal_eval(unsafe_expression) except ValueError as e:     print("Error:", e) 

Output
{'name': 'Aditya', 'age': 24} Error: malformed node or string on line 1: <ast.Call object at 0x7f27f021e2d0> 

Explanation: ast.literal_eval() safely evaluates only literals (strings, numbers, tuples, lists, dicts, booleans, None). It converts a JSON-like string into a dictionary and prevents arbitrary code execution by raising a ValueError for unsafe expressions.

Key Features of ast.literal_eval()

  • Safe: It only evaluates literals, which ensures that no arbitrary code is executed, reducing the risk of security vulnerabilities.
  • Limited scope: It can only parse Python literals and does not evaluate arbitrary expressions or function calls.
  • Ideal for data parsing: It is commonly used when you need to safely convert a string representation of a Python literal into its corresponding data type, such as when reading data from JSON-like formats.

Key difference between eval() and ast.literal_eval

Featureeval()ast.literal_eval
PurposeEvaluate arbitrary Python expressions and code.Safely evaluate Python literals like strings, numbers, lists, etc.
SecurityUnsafe, as it can execute arbitrary code.Safe, as it only evaluates literals and raises an error for non-literal expressions.
ScopeCan evaluate any valid Python code, including function calls and loops.Only evaluates simple data structures and literals.
Use CasesDynamic code execution, real-time expression evaluation.Parsing input that represents basic Python data types safely.
PerformanceSlower due to dynamic nature and broad functionality.Faster since it only evaluates literals.
Error HandlingMay silently execute malicious code if not handled properly.Raises an error if the input isn't a valid Python literal.

When to Use eval() and ast.literal_eval()

  • Use eval(): When you need to evaluate expressions dynamically, and you can ensure that the input is safe and trustworthy.
  • Use ast.literal_eval(): When you need to safely convert a string representation of a basic Python literal into its corresponding data structure. It’s ideal for deserializing input from external sources, such as APIs, user forms, or configuration files, where safety is a concern.

Security Implications and Best Practices

  • Never use eval() on untrusted input (e.g., user input, data from APIs, or external files) to prevent code injection attacks.
  • Prefer ast.literal_eval() for safely evaluating string-based data into Python objects.
  • Consider safer alternatives like json.loads() or yaml.safe_load() for structured data formats.

Next Article
Difference between != and is not operator in Python

A

adishakw28p
Improve
Article Tags :
  • Python
  • Python-Functions
Practice Tags :
  • python
  • python-functions

Similar Reads

  • Difference between List and Array in Python
    In Python, lists and arrays are the data structures that are used to store multiple items. They both support the indexing of elements to access them, slicing, and iterating over the elements. In this article, we will see the difference between the two. Operations Difference in Lists and ArraysAccess
    6 min read
  • Difference between == and is operator in Python
    In Python, == and is operators are both used for comparison but they serve different purposes. The == operator checks for equality of values which means it evaluates whether the values of two objects are the same. On the other hand, is operator checks for identity, meaning it determines whether two
    4 min read
  • Difference between != and is not operator in Python
    In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Whereas is not operator checks whether id() of two objects is same or not. If
    3 min read
  • Python: Difference between dir() and help()
    In Python, the dir() and help() functions help programmers understand objects and their functionality. dir() lists all the attributes and methods available for an object, making it easy to explore what it can do.help() provides detailed information about an object, including descriptions of its meth
    5 min read
  • Difference between + and , Python Print
    In this article, we will learn about the difference between + and, in Python print, The print() function in Python is used to print some messages as the output on the screen. We can print a single element or even multiple elements on the screen. Python provides two ways to print multiple elements as
    3 min read
  • Difference between end and sep in Python
    In this article we will discuss the difference between The end and sep are two parameters in Python's built-in print() function that will help to control how the output is formatted. end in PythonThe end is a parameter in Python's built-in print() function that controls what character(s) are printed
    2 min read
  • Difference between 'and' and '&' in Python
    and is a Logical AND that returns True if both the operands are true whereas '&' is a bitwise operator in Python that acts on bits and performs bit-by-bit operations. Note: When an integer value is 0, it is considered as False otherwise True when used logically. and in PythonThe 'and' keyword in
    6 min read
  • Difference between return and print in Python
    In Python, we may use the print statements to display the final output of a code on the console, whereas the return statement returns a final value of a function execution which may be used further in the code. In this article, we will learn about Python return and print statements. Return Statement
    2 min read
  • Difference between List and Dictionary in Python
    Lists and Dictionaries in Python are inbuilt data structures that are used to store data. Lists are linear in nature whereas dictionaries stored the data in key-value pairs. In this article, we will see the difference between the two and find out the time complexities and space complexities which ar
    6 min read
  • Python - Difference between := and ==
    In this article, we will be discussing the major differences between Walrus(:=) and the Comparison operator (==) := in PythonThe := operator in Python, also known as the walrus operator or assignment expression, was introduced in Python 3.8. It enables assignment and evaluation to happen simultaneou
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences