Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python3
communitycreator
abstractsyntaxtree

What is ast.literal_eval(node_or_string) in Python?

Adnan Abbas

Python ast module

The ast module (Abstract Syntax Tree)tree representation of source code allows us to interact with and modify Python code. Python comes with abstract syntax grammar that is subject to change with every Python release.

The ast module helps applications to process trees of syntax and find out what current syntax grammar looks like programmatically. Abstract syntax trees are great tools for program analysis and program transformation systems.

ast.literal_eval method

The ast.literal_eval method is one of the helper functions that helps traverse an abstract syntax tree. This function evaluates an expression node or a string consisting of a Python literal or container display.

The ast.literal_eval method can safely evaluate strings containing Python values from unknown sources without us having to parse the values. However, complex expressions involving indexing or operators cannot be evaluated using this function.

Parameters

node_or_string: The node or string that is to be evaluated. It may consist of the following Python literal structures:

  • strings
  • bytes
  • numbers
  • tuples
  • lists
  • dicts
  • sets
  • booleans
  • None and Ellipsis.

Code

The following Python code illustrates an example of the ast.literal_eval helper method:

import ast
dictionary = ast.literal_eval("{'a': 1, 'b': 2}")
print (type(dictionary))
print (dictionary)
ast.literal_eval in Python

Explanation

  • In this example, we evaluate a string that contains a Python dictionary.

  • As the output suggests, the ast.literal_eval method successfully evaluates the string, and gets the Python dictionary object.

RELATED TAGS

python3
communitycreator
abstractsyntaxtree
RELATED COURSES

View all Courses

Keep Exploring