Skip to content

Python eval alternative

  • by

If you’re looking for an alternative to the eval() function in Python, there are a few options you can consider depending on your specific use case. Here are a couple of alternatives:

ast.literal_eval(): This function from the ast module can safely evaluate a subset of Python expressions consisting of literals such as strings, numbers, tuples, lists, dictionaries, booleans, and None. It provides a safer alternative to eval() as it only evaluates literal expressions and does not execute arbitrary code.

import ast

expression = "[1, 2, 3]"
result = ast.literal_eval(expression)
print(result)# [1, 2, 3]

Parser libraries: If you need to evaluate more complex expressions or perform advanced computations, you might consider using a parser library like pyparsing, ply, or antlr. These libraries allow you to define a grammar for your expressions and parse them into an abstract syntax tree (AST). You can then traverse the AST and evaluate the expressions according to your requirements.

from pyparsing import Literal, Word, nums, infixNotation

# Define the grammar
integer = Word(nums).setParseAction(lambda t: int(t[0]))
plus = Literal("+")
minus = Literal("-")
operand = integer | '(' + infixNotation(integer, [(plus | minus, 2, infixNotation.opAssoc.LEFT)]) + ')'

# Evaluate the expression
expression = "2 + 3 * (4 - 1)"
result = operand.parseString(expression, parseAll=True)[0]
print(result)  # 11

Python eval alternative example

Here’s an example of how to use ast.literal_eval():

import ast

def safe_eval(expression):
        result = ast.literal_eval(expression)
        return result
    except (ValueError, SyntaxError) as e:
        print(f"Error occurred: {e}")
        return None

# Example usage
expression1 = "2 + 2"
result1 = safe_eval(expression1)
print(f"Result: {result1}")

expression2 = "'Hello, world!'"
result2 = safe_eval(expression2)
print(f"Result: {result2}")

expression3 = "[1, 2, 3]"
result3 = safe_eval(expression3)
print(f"Result: {result3}")

expression4 = "__import__('os').system('rm -rf /')"
result4 = safe_eval(expression4)
print(f"Result: {result4}")


Python eval alternative

Using ast.literal_eval() helps mitigate the security risks associated with using eval(), as it only evaluates literals and cannot execute arbitrary code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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