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      '' 
Answer from vaultah on Stack Overflow
🌐
Invicti
invicti.com › web-application-vulnerabilities › code-evaluation-python
Code Evaluation (Python) - Web Application Vulnerabilities | Invicti
# Vulnerable - DO NOT USE user_input = request.GET['calculation'] result = eval(user_input) # Allows arbitrary code execution Example - Safe Alternative:
🌐
Sourcery
sourcery.ai › vulnerabilities › python-lang-security-audit-eval-detected
Python eval() Function Detection Vulnerability | Security Vulnerability Database | Sourcery
Application uses the eval() function which can execute arbitrary Python code, creating serious security risks including remote code execution when processing untrusted input. ... from flask import Flask, request @app.route('/calculate') def ...
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.

🌐
Coventry University
github.coventry.ac.uk › pages › aa9863 › 5063CEM › 3_LinuxAndShells › RCE
Web Shells - 5063CEM: Practical Pen Testing
Depending on the types of command that can be run, the severity of a RCE attack can be major, with the attacker able to gain remote access to the target server. Lets start with a non web based example, we can do in the command line. Python (and many other languages) have the eval() function.
🌐
Floyd
floyd.ch
Exploiting Python’s Eval | floyd's
python module evalidate (pip3 install evalidate) solves this problem. It parses untrusted user code into Abstract Syntax Tree (AST) and checks each node. Code is evaluated then only if it consist only of safe nodes.
🌐
Reddit
reddit.com › r/learnpython › why is exec() and eval() not considered good practice?
r/learnpython on Reddit: Why is exec() and eval() not considered good practice?
July 27, 2024 -

Fairly new to coding and I am making a simple dungeon crawler with Python for a school project.

Since it will include a range of weapons which are objects, I'm currently using

thing = eval(nameOfWeapon + ".get_itemStat()")

(where nameOfWeapon is a variable so I can use this code for any item the player wants to access)

and things similar to that. This feels the most straightforward to me out of my own knowledge, but all sources online consider this a bad practice.

Is there a reason for this or alternatives that are considered better practice? This project will be getting graded so I don't want to lose marks if it's considered a python cardinal sin or something.

🌐
Pyre-check
pyre-check.org › 5001 - code injection
5001 - Code Injection | Pyre
The simplest kind of RCE involves user input flowing into a function such as eval or exec which are intended to interpret or run python code.
Find elsewhere
🌐
Medium
medium.com › @nikomanousos123 › exploiting-pythons-eval-function-69f8fc4074a1
Exploiting Python’s Eval Function | by Niko | Medium
July 7, 2025 - If you are new to Python, a built-in function is a function that is pre-built into the language, and you don’t need to import extra headers or libraries to use it. Eval works by taking a string argument, and will evaluate it and return the result.
🌐
Medium
medium.com › @debasissadhu712 › picoctf-3v-l-writeup-exploiting-python-eval-for-rce-bypassing-regex-ce85f1dc8c1e
picoCTF 3v@l Writeup: Exploiting Python eval() for RCE (Bypassing Regex) | by Debashish Sadhu | Medium
December 11, 2025 - The goal is simple but deadly: turn a standard input field into Remote Code Execution (RCE). However, there’s a catch — the server is protected by a strict regex filter/blacklist that blocks standard exploitation keywords.
🌐
Exploit Notes
exploit-notes.hdks.org › exploit › linux › privilege-escalation › python-eval-code-execution
Python Eval Code Execution - Exploit Notes
April 11, 2023 - Privilege Escalation (PrivEsc) is the act of exploiting a bug, a design flaw, or a configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. Once you have root privileges on Linux, you ...
🌐
GitHub
github.com › FoundationAgents › MetaGPT › issues › 1933
Remote Code Execution via eval() in Tree-of-Thought Solver · Issue #1933 · FoundationAgents/MetaGPT
February 4, 2026 - #!/usr/bin/env python3 """PoC: ToT eval() injection leads to RCE""" import re import os PROOF_FILE = "/tmp/tot_eval_rce_proof.txt" # Clean up if os.path.exists(PROOF_FILE): os.remove(PROOF_FILE) # Simulated malicious LLM response # This is what an LLM might return when influenced by prompt injection malicious_llm_response = f''' Here are the potential solutions: ```json __import__('os').system('id > {PROOF_FILE}') or [{{"node_id": "1", "node_state_instruction": "legitimate thought"}}] ''' pattern = r'[\w]*\n?(.*?)' match = re.search(pattern, malicious_llm_response, re.DOTALL) thoughts = match.group(1).strip() print(f"[*] Extracted from LLM response: {thoughts[:80]}...") thoughts = eval(thoughts) # RCE HAPPENS HERE!
Author   FoundationAgents
🌐
Blogger
vipulchaskar.blogspot.com › 2012 › 10 › exploiting-eval-function-in-python.html
Vipul Chaskar's Blog: Exploiting eval() function in Python
October 23, 2012 - I came across a pretty interesting function in python yesterday while coding. It is the eval() function. Basically it takes a string which has a valid python expression, and evaluates it as a regular python code.
🌐
Gitbook
morgan-bin-bash.gitbook.io › linux-privilege-escalation › python-eval-code-execution
Python Eval Code Execution | Linux Privilege Escalation
If the Python script allows us to input some value to the "text" variable, we can inject arbitrary code. Most of the time, we need to bypass another expression to execute our desired command. ... __import__('os').system('id') <!-- Bypass another expression in eval --> ),__import__('os').system('id') '),__import__('os').system('id') },__import__('os').system('id') ),__import__('os').system('id')# Copied!
🌐
Medium
medium.com › swlh › hacking-python-applications-5d4cd541b3f1
Hacking Python Applications. And how attackers exploit common… | by Vickie Li | The Startup | Medium
November 15, 2019 - Dangerous functions in Python like eval(), exec() and input() can be used to achieve authentication bypass and even code injection.
🌐
Blogger
sethsec.blogspot.com › 2016 › 11 › exploiting-python-code-injection-in-web.html
Exploiting Python Code Injection in Web Applications
November 20, 2016 - Python code injection is a subset of server-side code injection, as this vulnerability can occur in many other languages (e.g., Perl and Ruby). In fact, for those of you who are CWE fans like I am, these two CWEs are right on point: CWE-94: Improper Control of Generation of Code ('Code Injection') CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
🌐
Coventry University
github.coventry.ac.uk › pages › CUEH › 245CT › 2_LinuxAndShells › RCE
Web Shells and Remote Code Execution
Depending on the types of command that can be run, the severity of a RCE attack can be major, with the attacker able to gain remote access to the target server. Lets start with a non web based example, we can do in the command line. Python (and many other languages) have the eval() function.
🌐
YouTube
youtube.com › watch
Python Eval Function Exploitation | TryHackMe Devie - YouTube
In this video walk-through, we covered a scenario that demonstrates python exploitation through Eval function. Additionally we covered an example of XOR encr...
Published   April 5, 2023