Fundamentals 9 min read

Mastering Python’s eval(): How It Works, Uses, and Security Risks

This article explains Python's eval function, its syntax and parameters, demonstrates how it parses and evaluates expressions, shows practical examples with globals and locals, and discusses important security considerations when executing dynamic code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Python’s eval(): How It Works, Uses, and Security Risks

What is eval in Python?

The eval function evaluates a string as a Python expression. Its syntax is eval(expression, globals=None, locals=None), where expression is a string, globals is an optional dictionary of global names, and locals is an optional dictionary of local names.

How eval works

When called, eval parses the expression, compiles it to bytecode, evaluates the bytecode, and returns the result.

Basic examples

num = "23"
float_num = "53.332"
complex_num = "2+3j"
str1 = "Not number"
print(eval(num), type(eval(num)))
print(eval(float_num), type(eval(float_num)))
print(eval(complex_num), type(eval(complex_num)))
print(eval(str1), type(eval(str1)))

The first three calls convert the string to an int, float, and complex number; the last call raises a SyntaxError because the string is not a valid Python expression.

Evaluating mathematical expressions

expr = "(2+(3*2))/2"
print(eval(expr))  # 4.0

Using globals

num1 = 100  # a global variable
print(eval("num1 + 100", {"num1": num1}))
num2 = 200
print(eval("num1 + num2", {"num1": num1, "num2": num2}))
print(eval("num1 + num2", {"num1": num1}))  # raises NameError

Using locals

print(eval("sum([a, 2, 2])", {}, {"a": 2}))  # 6

Restricting built‑ins

print(eval('abs(-1)', {"__builtins__": None}, {"abs": abs}))  # 1

Security considerations

The eval function can execute arbitrary code, which makes it unsafe for untrusted input. For example, a malicious user could run __import__('subprocess').getoutput('rm -rf *') to delete files on the server.

To mitigate risks, avoid eval when possible, or tightly control the globals and locals dictionaries so that only safe functions (e.g., abs, min, sum) are available.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonSecurityTutorialglobalslocalsCode Executioneval
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.