Python eval(): Execute a String as Code

The eval() function takes a string and runs it as Python code, returning the result. It’s useful for dynamic expressions, mathematical calculations, and evaluating user input safely.

Example

expression = "5 + 10"
result = eval(expression)
print(result)  
# Output: 15

This converts the string into code and runs it.

Syntax

eval(expression, globals=None, locals=None)
  • expression → A string containing a Python expression.
  • globals (optional) → A dictionary of global variables (default: current scope).
  • locals (optional) → A dictionary of local variables (default: current scope).

1. Using eval() for Mathematical Expressions

Great for user-defined calculations.

user_input = "10 * (5 + 3)"
result = eval(user_input)
print(result)  
# Output: 80

Useful when building calculators or dynamic input systems.

2. Evaluating Lists and Dictionaries from Strings

Convert string representations of lists and dictionaries into real objects.

list_str = "[1, 2, 3, 4]"
numbers = eval(list_str)
print(numbers[2])  
# Output: 3

Handy for parsing stored data from text files or databases.

3. Using Variables in eval() with a Safe Scope

Limit what eval() can access using custom variables.

x = 10
safe_scope = {"x": x}
print(eval("x + 5", safe_scope))  
# Output: 15

This prevents security risks by restricting the available variables.

4. Preventing Security Risks

eval() can run malicious code if used carelessly. Never use it with untrusted input.

user_input = "__import__('os').system('rm -rf /')"  # Dangerous command
# eval(user_input)  # ⚠️ DO NOT RUN! Can delete files.

Instead, use a restricted scope to prevent access to system functions.

Key Notes

  • Executes strings as code – great for dynamic expressions.
  • Can convert lists, dictionaries, and tuples from strings.
  • Use with a restricted scope to avoid security risks.
  • Avoid using with user input unless necessary.

By using eval() carefully, you can handle dynamic code execution efficiently, but always ensure security precautions. 🚀

Leave a Comment

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

Scroll to Top