Safest Bet: `ast.literal_eval` for Python Literals
`ast.literal_eval()` from Python's `ast` module safely evaluates strings containing only standard Python literal structures like lists, dictionaries, numbers, and strings, preventing arbitrary code execution that `eval()` allows.
The top 3
- Top Python Literals `ast.literal_eval` Safely Parses: This function securely converts string representations of core Python data types including numbers, strings, lists, tuples, dictionaries, sets, booleans (True/False), None, and Ellipsis into their corresponding Python objects.
- How `ast.literal_eval` Prevents Code Injection Risks: Unlike the dangerous `eval()` function, `ast.literal_eval` explicitly rejects any input containing arbitrary code execution, function calls, variable lookups, or operations. This strict validation raises a `ValueError`, effectively preventing malicious code injection from untrusted sources.
- Beyond Literals: What `ast.literal_eval` Won't Parse: `ast.literal_eval` explicitly rejects any input that contains non-literal Python expressions, function calls, imports, or attribute access, which would be executable by `eval()`. For instance, expressions like "1 + 1", function calls like "__import__('os').system('rm -rf /')", or `dict()` will raise a `ValueError` or `SyntaxError` because they go beyond simple data structures.
Sources
Open the full topic