How to Use eval Function in Python: Syntax and Examples
The
eval() function in Python takes a string expression and runs it as Python code, returning the result. Use it by passing a string containing a valid Python expression, like eval('2 + 3'), which returns 5.Syntax
The eval() function syntax is simple:
eval(expression, globals=None, locals=None)
expression: A string containing a Python expression to evaluate.
globals and locals: Optional dictionaries to specify the global and local variables available during evaluation.
python
result = eval('3 * 4 + 5') print(result)
Output
17
Example
This example shows how eval() evaluates a string expression and returns the result.
python
expression = '10 + 20 / 5' result = eval(expression) print(f"The result of '{expression}' is {result}")
Output
The result of '10 + 20 / 5' is 14.0
Common Pitfalls
Using eval() can be risky because it runs any code given as a string, which can be dangerous if the input is from an untrusted source. Avoid using eval() on user input without strict validation.
Also, eval() only works with expressions, not statements like for loops or if blocks.
python
user_input = 'os.system("rm -rf /")' # Dangerous! # Dangerous use: # eval(user_input) # NEVER run this on untrusted input # Safer alternative: use literal_eval for literals only from ast import literal_eval safe_input = '[1, 2, 3]' result = literal_eval(safe_input) print(result)
Output
[1, 2, 3]
Quick Reference
Tips for using eval() safely and effectively:
- Only use
eval()with trusted input. - Use
globalsandlocalsparameters to control the environment. - For simple data structures, prefer
ast.literal_eval()which is safer. - Remember
eval()evaluates expressions, not statements.
Key Takeaways
Use
eval() to run Python expressions given as strings and get their results.Never use
eval() on untrusted input to avoid security risks.Use
globals and locals to limit the evaluation environment.For safe parsing of literals, prefer
ast.literal_eval() instead of eval().eval() works only with expressions, not full Python statements.