Eval and Exec Dangers — ELI5
Imagine you have a robot helper at home. You can give it instructions on sticky notes: “clean the kitchen,” “water the plants,” “lock the front door.” The robot follows whatever note you leave.
Now imagine you put a box outside your door that says “anyone can leave instructions for the robot.” A neighbor might write “water the plants” — nice! But a stranger could write “unlock the front door and open all the windows.”
That is exactly what eval() and exec() do in Python. They take a piece of text and run it as code. If that text comes from you, the programmer, it is fine. But if it comes from someone else — a website visitor, a form submission, a file you downloaded — you are letting a stranger write instructions for your computer.
And the computer follows instructions perfectly. It does not stop and think “this seems dangerous.” It just does what it is told.
The scary part is that the stranger’s code runs with all the same power your program has. It can read files, delete things, send data over the internet, or install software. There is no safety fence.
This is why experienced programmers treat eval() and exec() like fire — useful in controlled situations, but never left unattended around anything you do not fully trust.
One thing to remember: eval() and exec() turn text into running code. If that text comes from an untrusted source, you are giving a stranger full control of your program. Almost always, there is a safer way to accomplish what you need.
See Also
- Ci Cd Why big apps can ship updates every day without turning your phone into a glitchy mess — CI/CD is the behind-the-scenes quality gate and delivery truck.
- Containerization Why does software that works on your computer break on everyone else's? Containers fix that — and they're why Netflix can deploy 100 updates a day without the site going down.
- Python 310 New Features Python 3.10 gave programmers a shape-sorting machine, friendlier error messages, and cleaner ways to say 'this or that' in type hints.
- Python 311 New Features Python 3.11 made everything faster, error messages smarter, and let you catch several mistakes at once instead of stopping at the first one.
- Python 312 New Features Python 3.12 made type hints shorter, f-strings more powerful, and started preparing Python's engine for a world without the GIL.