eval and exec

Dynamic code execution

Interview Relevant: Advanced usage

eval and exec

Execute strings as Python code (use with caution!).

Code Examples

Dynamic code execution (use carefully!).

python
1# eval - evaluate expression
2eval("2 + 2")     # 4
3eval("len([1,2,3])")  # 3
4
5x = 10
6eval("x * 2")     # 20
7
8# exec - execute statements
9exec("y = 5")     # Creates variable y
10exec("""
11def greet():
12    print("Hello!")
13greet()
14""")
15
16# SECURITY WARNING!
17# Never use eval/exec with user input!
18# eval(user_input)  # DANGEROUS!
19
20# Safer alternatives
21import ast
22ast.literal_eval("[1, 2, 3]")  # Safe for literals
23
24# Use for specific needs only
25allowed_names = {"min": min, "max": max}
26eval("min(1, 2)", {"__builtins__": {}}, allowed_names)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In