Intermediate LevelPython
Why is dynamic code execution via eval() and exec() dangerous and how do you parse expressions safely with ast.literal_eval()?
❓ Interview Prompt: Explain `eval()`, `exec()`, Code Injection security vulnerabilities, and `ast.literal_eval()` for safely parsing string literals.
1. 'eval()' and 'exec()' (Dangerous!):
Dynamically execute arbitrary Python source code strings with full system privileges. Untrusted input can execute '__import__('os').system('rm -rf /')'!
2. 'ast.literal_eval()' (Secure!):
Safely evaluates strings containing Python literals (strings, numbers, tuples, lists, dicts, booleans) without risk of code execution.
Code Implementation Example
python
import ast
user_input = "[1, 2, 3, {'a': 'b'}]"
# SAFE: Safely parses stringified Python literal structure without code execution!
safe_data = ast.literal_eval(user_input)
print(type(safe_data)) # <class 'list'>💡Safely parsing stringified Python structures using ast.literal_eval().
🎯 Interview Key Takeaway
Never use eval() on untrusted user input; use ast.literal_eval() to safely parse stringified literals.
#ast.literal_eval#eval#Security#Intermediate
Back to all Python Questions→