# 15 Underrated Python Libraries You've Probably Never Heard Of

Everyone knows `requests`, `pandas` and `NumPy`. This post is about the other shelf: small, focused libraries that quietly replace a pile of boilerplate, and that most developers only discover by accident.

Each entry has the problem it solves, a short example, and the one thing worth knowing before you adopt it. All examples assume a recent Python 3 (3.10+).

![Mermaid Diagram](https://mermaid.ink/img/pako:eNpdkTtvGzEMx78Ky1k3BOjkIUVsx0iHLnEfgy8DT0fdEdHjKvFqu4G_eyFf4AIZJfz-D5JvaFPPuELn09GOlBW-b9sIAPBwaPHXSAqUGc5pBifDqBIHOIqOX1p8gaa5h_WhxS0pAcUeiubZ6py5tPjybnOlNtWMO5ho4HJFlU_6AdoeWtyJfweKpkwDf2Aeaxx38zDUJotRqa1u3HqpdXdocfApGOiZp16cMxDKUCa2BiaJ_8M3S8MqKOzZavJ0MqCZnHjSOZOBiXJhA07d-abbLqWrrpfyasmObKBLXlMsBspvL8rNrOKLgSOpHV0d7qZ_XAaq-uksse4ucFQDYtlmpmBAJXATyI4S6yLQYOAcSHpcvaGOHOrpenY0e0Wz_PykLNR5LpVxKeqOgvgzrrChafLclHNRDgbWXuLrN7L763uXanSLex4Sw4-vLRp4Tl3SZOCJ_R9WsWTgIQt5A4ViaQpncWiuIXv5W7vcfZ5OeLkY7IZN8injCj8dR1HGyz8ADMkv?type=png)

* * *

## Data and structures

### 1\. glom: query and reshape nested data

**Problem:** `data["customer"]["emails"][0]["addr"]` dies with a `KeyError` at the first missing key, and nested list comprehensions get unreadable fast.

```python
from glom import glom

order = {
    "id": 42,
    "customer": {"name": "Asha", "emails": [{"addr": "asha@example.com"}, {"addr": "a@work.io"}]},
    "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}],
}

glom(order, "customer.name")                      # 'Asha'
glom(order, ("customer.emails", ["addr"]))        # ['asha@example.com', 'a@work.io']
glom(order, {"who": "customer.name", "skus": ("items", ["sku"])})
# {'who': 'Asha', 'skus': ['A1', 'B7']}
glom(order, "customer.phone", default=None)       # None
```

**Worth knowing:** when a path fails, the error shows exactly where in the structure it broke, which is a big help with messy third-party JSON.

```bash
pip install glom
```

### 2\. DeepDiff: see exactly what changed between two objects

**Problem:** `old == new` tells you they differ, not _how_.

```python
from deepdiff import DeepDiff

old = {"id": 1, "price": 10, "tags": ["a", "b"]}
new = {"id": 1, "price": 12, "tags": ["a", "b", "c"], "currency": "INR"}

print(DeepDiff(old, new))
# {'dictionary_item_added': [root['currency']],
#  'values_changed': {"root['price']": {'new_value': 12, 'old_value': 10}},
#  'iterable_item_added': {"root['tags'][2]": 'c'}}
```

**Worth knowing:** options like `ignore_order=True` and `exclude_paths=[...]` let you ignore list ordering and noisy fields (timestamps, request IDs). That makes it a good fit for detecting when an API quietly changes its response shape.

```bash
pip install deepdiff
```

### 3\. msgspec: fast, typed JSON decoding with validation

**Problem:** you want typed objects from JSON without paying a heavy validation cost on every request.

```python
import msgspec

class User(msgspec.Struct):
    id: int
    name: str
    email: str | None = None

user = msgspec.json.decode(b'{"id": 1, "name": "Asha"}', type=User)
print(user)                      # User(id=1, name='Asha', email=None)
print(msgspec.json.encode(user)) # b'{"id":1,"name":"Asha","email":null}'
```

**Worth knowing:** decoding and validating happen in one pass, and a bad payload raises a `ValidationError` that names the offending field. It's much lighter than most alternatives; its own benchmarks show a large speed gap. It's less feature-rich than Pydantic, so pick it when throughput and memory matter more than ecosystem.

```bash
pip install msgspec
```

### 4\. Pint: units that can't be mixed up by accident

**Problem:** a bare `float` doesn't know whether it's metres, feet or hours. (The Mars Climate Orbiter was lost in 1999 over a pound-force vs newton unit mismatch.)

```python
import pint

ureg = pint.UnitRegistry()

distance = 5 * ureg.kilometer
duration = 20 * ureg.minute
print((distance / duration).to("km/hour"))   # 15.0 kilometer / hour

5 * ureg.meter + 3 * ureg.second             # raises DimensionalityError
```

**Worth knowing:** conversions and dimensional checks come for free, so unit bugs fail loudly instead of silently producing wrong numbers.

```bash
pip install pint
```

* * *

## Web pages and text

### 5\. selectolax: a much faster HTML parser

**Problem:** BeautifulSoup is friendly but slow when you're parsing thousands of large pages.

```python
from selectolax.parser import HTMLParser

tree = HTMLParser(html)
title = tree.css_first("h1").text(strip=True)
prices = [n.text(strip=True) for n in tree.css("span.price")]
```

**Worth knowing:** it wraps fast C engines (Modest, with a Lexbor backend available) and uses CSS selectors only, no XPath. `css_first` returns `None` when nothing matches, so check before calling `.text()`.

```bash
pip install selectolax
```

### 6\. trafilatura: extract the actual article from a web page

**Problem:** you want the main text of a page without the navigation, cookie banners, ads and footers. This is exactly what scrapers and RAG pipelines need.

```python
import trafilatura

html = trafilatura.fetch_url("https://example.com/some-article")
text = trafilatura.extract(html, include_comments=False, include_tables=False)
meta = trafilatura.extract_metadata(html)   # title, author, date, etc. when available
```

**Worth knowing:** it also has a CLI (`trafilatura -u <url>`) and handles feeds and sitemaps, and it scores well in published content-extraction comparisons. Always respect `robots.txt` and rate limits when crawling.

```bash
pip install trafilatura
```

### 7\. parse: the opposite of `str.format()`

**Problem:** you have semi-structured text (logs, filenames, CLI output) and a regex would be overkill to write and impossible to read.

```python
from parse import parse

line = "2026-11-28 14:03:11 ERROR payments: card declined order=9913"
r = parse("{date} {time} {level} {module}: {msg} order={order:d}", line)

r["level"], r["order"]    # ('ERROR', 9913)
```

**Worth knowing:** the `:d` converts to `int`, and `parse` returns `None` when the line doesn't match, which makes it easy to skip junk lines. `search()` and `findall()` cover partial matches.

```bash
pip install parse
```

### 8\. ftfy: fix broken text automatically

**Problem:** scraped or exported text full of `✔`, `é` and `&amp;` junk (mojibake from the wrong encoding being applied somewhere).

```python
import ftfy

ftfy.fix_text("✔ No problems")   # '✔ No problems'
```

**Worth knowing:** it's designed to fix text that is _already_ garbled and to leave good text alone, so it's safe to run over a whole dataset as a cleanup step.

```bash
pip install ftfy
```

* * *

## Files and storage

### 9\. diskcache: a persistent cache with no server

**Problem:** you want caching that survives restarts and is shared between processes, but Redis feels like overkill.

```python
from diskcache import Cache

cache = Cache("/tmp/api-cache")

@cache.memoize(expire=3600)
def fetch_rates(day: str):
    ...  # slow API call

cache.set("last_run", "2026-11-28", expire=60)
cache.get("last_run")
```

**Worth knowing:** it's backed by SQLite and plain files, and is thread-safe and process-safe. It's a great fit for scripts, cron jobs and local tools.

```bash
pip install diskcache
```

### 10\. boltons: the missing standard-library pieces

**Problem:** you keep rewriting the same small helpers: atomic file writes, chunking, LRU caches, walking nested data.

```python
import json
from boltons.fileutils import atomic_save
from boltons.iterutils import chunked

# Writes to a temp file, then swaps it in: no half-written state.json after a crash
with atomic_save("state.json", text_mode=True) as f:
    f.write(json.dumps({"cursor": 1200}))

list(chunked(range(7), 3))   # [[0, 1, 2], [3, 4, 5], [6]]
```

**Worth knowing:** it's pure Python with zero dependencies. `iterutils.remap` (transform deeply nested structures), `cacheutils.LRU` and `strutils.slugify` are other favourites.

```bash
pip install boltons
```

### 11\. sqlite-utils: a database in two lines

**Problem:** you have JSON or CSV and want to query, search and join it with SQL without designing a schema first.

```python
import sqlite_utils

db = sqlite_utils.Database("app.db")
db["orders"].insert_all(rows, pk="id", alter=True)   # creates and extends the table for you
db["orders"].enable_fts(["customer", "notes"], create_triggers=True)

list(db["orders"].search("refund"))                  # full-text search
```

```bash
sqlite-utils insert app.db orders orders.json --pk=id
sqlite-utils query app.db "select customer, sum(total) from orders group by 1"
```

**Worth knowing:** `alter=True` adds columns as new keys appear, which is handy for evolving data. It's built by Simon Willison, the creator of Datasette.

```bash
pip install sqlite-utils
```

### 12\. watchfiles: react to file changes

**Problem:** you want to re-run something when files change, without polling loops or flaky watchers.

```python
from watchfiles import watch

for changes in watch("./content"):
    for change, path in changes:
        print(change.name, path)    # added / modified / deleted
```

```bash
watchfiles "python build.py" content/
```

**Worth knowing:** it's built on Rust's `notify` library, has async support (`awatch`), and is what `uvicorn --reload` uses when it's installed.

```bash
pip install watchfiles
```

* * *

## Debugging and testing

### 13\. pyinstrument: a profiler you can actually read

**Problem:** `cProfile` output is a wall of numbers, and it's hard to see _which call path_ is slow.

```python
from pyinstrument import Profiler

profiler = Profiler()
profiler.start()
main()
profiler.stop()
profiler.print()               # call tree with time spent in each branch
# profiler.open_in_browser()   # interactive HTML view
```

```bash
pyinstrument script.py
```

**Worth knowing:** it's a sampling profiler, so overhead is low, and it ships Django middleware (a few lines wire it into Flask or FastAPI too). Profile a slow request and read the tree top-down.

```bash
pip install pyinstrument
```

### 14\. icecream: print debugging, but better

**Problem:** `print(f"x = {x}")` is tedious to type and tells you nothing about where it came from.

```python
from icecream import ic

def double(x):
    return x * 2

ic(double(21))
# ic| double(21): 42

ic()   # prints file, line and function: handy for "did we get here?"
```

**Worth knowing:** `ic` prints the expression _and_ its value. `ic.disable()` silences everything without removing the calls, so don't ship it in hot paths without that switch.

```bash
pip install icecream
```

### 15\. time-machine: test time-dependent code

**Problem:** trial expiries, invoice cutoffs and "run on the last day of the month" logic are painful to test against the real clock.

```python
import datetime as dt
import time_machine

def test_trial_expires():
    start = dt.datetime(2026, 1, 1, tzinfo=dt.timezone.utc)
    with time_machine.travel(start, tick=False) as traveller:
        trial = start_trial()
        traveller.shift(dt.timedelta(days=15))
        assert trial.is_expired()
```

**Worth knowing:** `tick=False` freezes the clock; leave it out to let time keep moving from the destination. It patches time at the C level, and its docs describe it as faster than freezegun on large test suites.

```bash
pip install time-machine
```

* * *

## Honorable mentions

`rapidfuzz` (fuzzy string matching), `more-itertools` (a much bigger `itertools`), `sortedcontainers` (sorted lists and dicts in pure Python) and `plotext` (charts in the terminal).

## Where to start

You don't need all fifteen. Pick the one that matches a problem you hit this week:

-   Drowning in nested JSON: **glom** or **DeepDiff**
    
-   Slow scraping or noisy page text: **selectolax** or **trafilatura**
    
-   Scripts that lose state when they crash: **boltons** (`atomic_save`) or **diskcache**
    
-   Code that's slow and you don't know why: **pyinstrument**
    

Install them all in a throwaway virtual environment and try them out:

```bash
pip install glom deepdiff msgspec pint selectolax trafilatura parse ftfy diskcache boltons sqlite-utils watchfiles pyinstrument icecream time-machine
```

## Wrap-up

None of these libraries is flashy, and that's the point. Each one removes a chunk of code you'd otherwise write, test and maintain yourself: nested lookups, diffing, caching, atomic writes, profiling. The best way to judge them is to try one on a real problem this week. If it saves you an hour, it has earned a place in your `requirements.txt`.

---

*Published via [ZyVOP](https://zyvop.com/15-underrated-python-libraries-you-ve-probably-never-heard-of-g9oem?utm_source=hashnode&utm_medium=crosspost&utm_campaign=syndication) — Write once in Markdown, auto-backup to GitHub, and syndicate to Dev.to, Medium & Hashnode in 1 click.*
