🌐
Codecademy
codecademy.com › docs › python › built-in functions › eval()
Python | Built-in Functions | eval() | Codecademy
July 11, 2025 - The eval() function is a built-in Python function that dynamically evaluates and executes Python expressions from string-based input.
🌐
Real Python
realpython.com › python-eval-function
Python eval(): Evaluate Expressions Dynamically – Real Python
October 21, 2023 - As you saw earlier, Python’s eval() automatically inserts a reference to the dictionary of builtins into globals before parsing expression.
🌐
Real Python
realpython.com › ref › builtin-functions › eval
eval() | Python’s Built-in Functions – Real Python
Language: Python · >>> def eval_expression(expression): ... code = compile(expression, "<string>", "eval") ... if code.co_names: ... raise NameError(f"Use of names not allowed") ... return eval(code, {"__builtins__": {}}, {}) ... >>> eval_expression("3 + 4 * 5 + 25 / 2") 35.5 >>> eval_expression("sum([1, 2, 3])") Traceback (most recent call last): ...
🌐
ThePythonGuru
thepythonguru.com › python-builtin-functions › eval
Python eval() function - ThePythonGuru.com
Even though we have passed empty dictionaries as global and local namespaces, eval() still has access to built-ins (i.e __builtins__ ).
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.6 documentation
Overriding __builtins__ can be used to restrict or change the available names, but this is not a security mechanism: the executed code can still access all builtins. If the locals mapping is omitted it defaults to the globals dictionary. If both mappings are omitted, the source is executed with the globals and locals in the environment where eval() is called.
🌐
Programiz
programiz.com › python-programming › methods › built-in › eval
Python eval()
If you pass an empty dictionary as globals, only the __builtins__ are available to expression (first parameter to the eval()).
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › eval.html
eval — Python Reference (The Right Way) 0.1 documentation
>>> # this example shows how to prevent eval from importing any modules >>> eval('__import__("os").getcwd()', {'__builtins__': {}}) Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "<string>", line 1, in <module> NameError: name '__import__' is not defined
🌐
Towards Data Science
towardsdatascience.com › home › latest › python eval() built-in-function
Python eval() built-in-function | Towards Data Science
January 20, 2025 - Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression.
Find elsewhere
Top answer
1 of 7
37

I'm going to mention one of the new features of Python 3.6 - f-strings.

They can evaluate expressions,

>>> eval('f"{().__class__.__base__}"', {'__builtins__': None}, {})
"<class 'object'>"

but the attribute access won't be detected by Python's tokenizer:

0,0-0,0:            ENCODING       'utf-8'        
1,0-1,1:            ERRORTOKEN     "'"            
1,1-1,27:           STRING         'f"{().__class__.__base__}"'
2,0-2,0:            ENDMARKER      '' 
2 of 7
24

It is possible to construct a return value from eval that would throw an exception outside eval if you tried to print, log, repr, anything:

eval('''((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))))
        (lambda f: lambda n: (1,(1,(1,(1,f(n-1))))) if n else 1)(300))''')

This creates a nested tuple of form (1,(1,(1,(1...; that value cannot be printed (on Python 3), stred or repred; all attempts to debug it would lead to

RuntimeError: maximum recursion depth exceeded while getting the repr of a tuple

pprint and saferepr fails too:

...
  File "/usr/lib/python3.4/pprint.py", line 390, in _safe_repr
    orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
  File "/usr/lib/python3.4/pprint.py", line 340, in _safe_repr
    if issubclass(typ, dict) and r is dict.__repr__:
RuntimeError: maximum recursion depth exceeded while calling a Python object

Thus there is no safe built-in function to stringify this: the following helper could be of use:

def excsafe_repr(obj):
    try:
        return repr(obj)
    except:
        return object.__repr__(obj).replace('>', ' [exception raised]>')

And then there is the problem that print in Python 2 does not actually use str/repr, so you do not have any safety due to lack of recursion checks. That is, take the return value of the lambda monster above, and you cannot str, repr it, but ordinary print (not print_function!) prints it nicely. However, you can exploit this to generate a SIGSEGV on Python 2 if you know it will be printed using the print statement:

print eval('(lambda i: [i for i in ((i, 1) for j in range(1000000))][-1])(1)')

crashes Python 2 with SIGSEGV. This is WONTFIX in the bug tracker. Thus never use print-the-statement if you want to be safe. from __future__ import print_function!


This is not a crash, but

eval('(1,' * 100 + ')' * 100)

when run, outputs

s_push: parser stack overflow
Traceback (most recent call last):
  File "yyy.py", line 1, in <module>
    eval('(1,' * 100 + ')' * 100)
MemoryError

The MemoryError can be caught, is a subclass of Exception. The parser has some really conservative limits to avoid crashes from stackoverflows (pun intended). However, s_push: parser stack overflow is output to stderr by C code, and cannot be suppressed.


And just yesterday I asked why doesn't Python 3.4 be fixed for a crash from,

% python3  
Python 3.4.3 (default, Mar 26 2015, 22:03:40) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...     def f(self):
...         nonlocal __x
... 
[4]    19173 segmentation fault (core dumped)  python3

and Serhiy Storchaka's answer confirmed that Python core devs do not consider SIGSEGV on seemingly well-formed code a security issue:

Only security fixes are accepted for 3.4.

Thus it can be concluded that it can never be considered safe to execute any code from 3rd party in Python, sanitized or not.

And Nick Coghlan then added:

And as some additional background as to why segmentation faults provoked by Python code aren't currently considered a security bug: since CPython doesn't include a security sandbox, we're already relying entirely on the OS to provide process isolation. That OS level security boundary isn't affected by whether the code is running "normally", or in a modified state following a deliberately triggered segmentation fault.

🌐
Execute Program
executeprogram.com › courses › python-in-detail › lessons › eval
Eval Lesson - Python in Detail
eval only works with expressions, so it doesn't support statements like if, for, def, or even variable assignment via =. (In Python, variable assignments are statements, not expressions, so they have no value.) Trying to eval a statement is an error. ... However, evaled code can still change data outside the eval statement. For example, it might call .append on a list. ... In an earlier lesson, we saw that built-ins like len are stored in the global __builtins__ dictionary.
🌐
Netsec
netsec.expert › posts › breaking-python3-eval-protections
Breaking Python 3 eval protections – Sam's Hacking Wonderland
January 16, 2021 - This is easy to verify by checking for something which does not exist either as a function or variable like, say ,‘potato’. Noting that it gives an error message, then assigning a potato function to the __builtins__ module and calling it and noting that it works. As a way to make eval slightly safer, the idea is that you can clear this __builtins__ variable to prevent dangerous built-in functions from being launched.
🌐
TutorialKart
tutorialkart.com › python › python-eval
Python eval() Builtin Function - Examples
April 3, 2023 - Python eval() builtin function is used to evaluate an expression that is given as a string. eval() can also execute code objects created by compile() method.
🌐
Nickdrozd
nickdrozd.github.io › 2023 › 10 › 27 › python-eval.html
eval should not be a built-in function | Something Something Programming
October 27, 2023 - This function accepts a string argument and returns the value of the string when evaluated as Python code. Built-in functions ought to be basic and broadly-applicable. But eval is neither: it is at once extraordinarily powerful and practically useless.
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › built-in › eval › python-eval
Python eval() | What is Python eval() function? | When is eval() used?
August 18, 2021 - Python eval() function is used to parse an expression as an argument and then execute it within the Python program. The Python eval() is a built-in function that allows us to evaluate the Python expression as a ‘string’ and return the value as an integer.
🌐
Medium
medium.com › @laurentkubaski › dynamically-evaluating-code-using-python-9821a24f98ce
Dynamically evaluating code using Python eval() | by Laurent Kubaski | Medium
September 2, 2025 - So to summarize, if you just call ... All the local variable & functions. All the builtin functions (including the __import__ function that allows dynamically importing any module)...
🌐
STechies
stechies.com › does-python-eval-function
What Does Python eval() Function Do?
March 24, 2020 - You can see if we run eval() function with empty directory still it has the access to builtin methods. So to restrict the user to use the limited function, you need to specify this function as global. ... # Python eval() function with global # Import math library from math import *; # Take input from user userInput = input("Enter Math Function to Evaluate.\nAllowed Functions are \nsamllIntegral(n)\nlargestIntegral(n)\nabs(n)\nfact(n)\n"); try: print(eval(userInput,{'samllIntegral':ceil,'largestIntegral':floor,'abs':fabs,'fact':factorial})) except Exception as excep: print(excep) print('Operation Done')
🌐
Reddit
reddit.com › r/python › valid uses of eval()?
r/Python on Reddit: Valid uses of eval()?
March 1, 2024 -

I’m wondering if anyone has ever seen a case of code using eval() and thought to themselves “yeah actually that’s probably the right way to do it”?

My understanding has always been that it’s a huge security risk and generally a recipe for disaster.

But I was just working on a task where I couldn’t really figure out any other way to achieve the dynamic functionality I was looking for, so I wrote code that assembles a string to do what I need, and then runs eval() on that string. Pretty sure this is the first time I’ve ever used eval() at all.

It’s a low-stakes proof of concept for a totally internal tool, so I’m not hugely worried about security at the moment, but it just feels so icky to do something like that. I’m curious if in others’ experience there’s always a better way than using eval(), or if sometimes it’s legit.

🌐
Codingem
codingem.com › home › python eval() function
Python eval() Function - codingem.com
November 3, 2022 - This is possible because when you call eval() with empty globals, a __builtins__ reference is automatically inserted into the globals dictionary.
🌐
KooR.fr
koor.fr › Python › API › python › builtins › eval.wp
KooR.fr - Fonction eval - module builtins - Description de quelques librairies Python
Vous êtes un professionnel et vous avez besoin d'une formation ? Machine Learning avec Scikit-Learn Voir le programme détaillé Module « builtins » Python 3.13.2 · def eval(expression: str, globals: dict[str:object] = None, locals: dict[str:object] = None) -> object