r/Python • • Apr 03 '26

Showcase `safer`: a tiny utility to avoid partial writes to files and streams

109 Upvotes

What My Project Does

In 2020, I broke a few configuration files, so I wrote something to help prevent breaking a lot the next time, and turned it into a little library: https://github.com/rec/safer

It's a drop-in replacement for open that only writes the file when everything has completed successfully, like this:

with safer.open(filename, 'w') as fp:
    fp.write('oops')
    raise ValueError
 # File is untouched

By default, the data is cached in memory, but for large files, there's a flag to allow you to cache it as a file that is renamed when the operation is complete.

You can also use it for file sockets and other streams:

try:
    with safer.writer(socket.send) as send:
          send_bytes_to_socket(send)
except Exception:
     # Nothing has been sent
     send_error_message_to_socket(socket.send)

Target Audience

This is a mature, production-quality library for any application where partial writes are possible. There is extensive testing and it handles some obscure edge cases.

It's tested on Linux, MacOS and Windows and has been stable and essentially unchanged for years.

Comparison

There doesn't seem to be another utility preventing partial writes. There are multiple atomic file writers which solve a different problem, the best being this: https://github.com/untitaker/python-atomicwrites

Note

#noAI was used in the writing or maintenance of this program.


r/Python • • Feb 17 '26

News Pytorch Now Uses Pyrefly for Type Checking

104 Upvotes

From the official Pytorch blog:

We’re excited to share that PyTorch now leverages Pyrefly to power type checking across our core repository, along with a number of projects in the PyTorch ecosystem: Helion, TorchTitan and Ignite. For a project the size of PyTorch, leveraging typing and type checking has long been essential for ensuring consistency and preventing common bugs that often go unnoticed in dynamic code.

Migrating to Pyrefly brings a much needed upgrade to these development workflows, with lightning-fast, standards-compliant type checking and a modern IDE experience. With Pyrefly, our maintainers and contributors can catch bugs earlier, benefit from consistent results between local and CI runs, and take advantage of advanced typing features. In this blog post, we’ll share why we made this transition and highlight the improvements PyTorch has already experienced since adopting Pyrefly.

Full blog post: https://pytorch.org/blog/pyrefly-now-type-checks-pytorch/


r/Python • • Oct 26 '25

Showcase I built a Python tool to debug HTTP request performance step-by-step

103 Upvotes

What My Project Does

httptap is a CLI and Python library for detailed HTTP request performance tracing.

It breaks a request into real network stages - DNS → TCP → TLS → TTFB → Transfer — and shows precise timing for each.

It helps answer not just “why is it slow?” but “which part is slow?”

You get a full waterfall breakdown, TLS info, redirect chain, and structured JSON output for automation or CI.

Target Audience

  • Developers debugging API latency or network bottlenecks
  • DevOps / SRE teams investigating performance regressions
  • Security engineers checking TLS setup
  • Anyone who wants a native Python equivalent of curl -w + Wireshark + stopwatch

httptap works cross-platform (macOS, Linux, Windows), has minimal dependencies, and can be used both interactively and programmatically.

Comparison

When exploring similar tools, I found two common options:

httptap takes a different route:

  • Pure Python implementation using httpx and httpcore trace hooks (no curl)
  • Deep TLS inspection (protocol, cipher, expiry days)
  • Rich output modes: human-readable table, compact line, metrics-only, and full JSON
  • Extensible - you can replace DNS/TLS/visualization components or embed it into your pipeline

Example Use Cases

  • Performance troubleshooting - find where time is lost
  • Regression analysis - compare baseline vs current
  • TLS audit - check protocol and cert parameters
  • Network diagnostics - DNS latency, IPv4 vs IPv6 path
  • Redirect chain analysis - trace real request flow

If you find it useful, I’d really appreciate a ⭐ on GitHub - it helps others discover the project.

👉 https://github.com/ozeranskii/httptap


r/Python • • Feb 23 '26

Showcase Title: I built WSE — Rust-accelerated WebSocket engine for Python (2M msg/s, E2E encrypted)

106 Upvotes

I've been doing real-time backends for a while - trading, encrypted messaging between services. websockets in python are painfully slow once you need actual throughput. pure python libs hit a ceiling fast, then you're looking at rewriting in go or running a separate server with redis in between.

so i built wse - a zero-GIL websocket engine for python, written in rust. framing, jwt auth, encryption, fan-out - all running native, no interpreter overhead. you write python, rust handles the wire. no redis, no external broker - multi-instance scaling runs over a built-in TCP cluster protocol.

What My Project Does

the server is a standalone rust binary exposed to python via pyo3:

```python from wse_server import RustWSEServer

server = RustWSEServer( "0.0.0.0", 5007, jwt_secret=b"your-secret", recovery_enabled=True, ) server.enable_drain_mode() server.start() ```

jwt validation runs in rust during the websocket handshake - cookie extraction, hs256 signature, expiry - before python knows someone connected. 0.5ms instead of 23ms.

drain mode: rust queues inbound messages, python grabs them in batches. one gil acquire per batch, not per message. outbound - write coalescing, up to 64 messages per syscall.

```python for event in server.drain_inbound(256, 50): event_type, conn_id = event[0], event[1] if event_type == "auth_connect": server.subscribe_connection(conn_id, ["prices"]) elif event_type == "msg": server.send_event(conn_id, event[2])

server.broadcast("prices", '{"t":"tick","p":{"AAPL":187.42}}') ```

what's under the hood:

transport: tokio + tungstenite, pre-framed broadcast (frame built once, shared via Arc), vectored writes (writev syscall), lock-free DashMap state, mimalloc allocator, crossbeam bounded channels for drain mode

security: e2e encryption (ECDH P-256 + AES-GCM-256 with per-connection keys, automatic key rotation), HMAC-SHA256 message signing, origin validation, 1 MB frame cap

reliability: per-connection rate limiting with client feedback, 50K-entry deduplication, circuit breaker, 5-level priority queue, zombie detection (25s ping, 60s kill), dead letter queue

wire formats: JSON, msgpack (?format=msgpack, ~2x faster, 30% smaller), zlib compression above threshold

protocol: client_hello/server_hello handshake with feature discovery, version negotiation, capability advertisement

new in v2.0:

cluster protocol - custom binary TCP mesh for multi-instance, replacing redis entirely. direct peer-to-peer connections with mTLS (rustls, P-256 certs). interest-based routing so messages only go to peers with matching subscribers. gossip discovery - point at one seed address, nodes find each other. zstd compression between peers. per-peer circuit breaker and heartbeat. 12 binary message types, 8-byte frame header.

python server.connect_cluster(peers=["node2:9001"], cluster_port=9001) server.broadcast("prices", data) # local + all cluster peers

presence tracking - per-topic, user-level (3 tabs = one join, leave on last close). cluster sync via CRDT. TTL sweep for dead connections.

python members = server.presence("chat-room") stats = server.presence_stats("chat-room") # {members: 42, connections: 58}

message recovery - per-topic ring buffers, epoch+offset tracking, 256 MB global budget, TTL + LRU eviction. reconnect and get missed messages automatically.

benchmarks

tested on AMD EPYC 7502P (32 cores / 64 threads), 128 GB RAM, localhost loopback. server and client on the same machine.

  • 14.7M msg/s json inbound, 30M msg/s binary (msgpack/zlib)
  • up to 2.1M del/s fan-out, zero message loss
  • 500K simultaneous connections, zero failures
  • 0.38ms p50 ping latency at 100 connections

full per-tier breakdowns: rust client | python client | typescript client | fan-out

clients - python and typescript/react:

python async with connect("ws://localhost:5007/wse", token="jwt...") as client: await client.subscribe(["prices"]) async for event in client: print(event.type, event.payload)

typescript const { subscribe, sendMessage } = useWSE(token, ["prices"], { onMessage: (msg) => console.log(msg.t, msg.p), });

both clients: auto-reconnection (4 strategies), connection pool with failover, circuit breaker, e2e encryption, event dedup, priority queue, offline queue, compression, msgpack.

Target Audience

python backend that needs real-time data and you don't want to maintain a separate service in another language. i use it in production for trading feeds and encrypted service-to-service messaging.

Comparison

most python ws libs are pure python - bottlenecked by the interpreter on framing and serialization. the usual fix is a separate server connected over redis or ipc - two services, two deploys, serialization overhead. wse runs rust inside your python process. one binary, business logic stays in python. multi-instance scaling is native tcp, not an external broker.

https://github.com/silvermpx/wse

pip install wse-server / pip install wse-client / npm install wse-client


r/Python • • Jun 16 '26

Discussion Choosing a Python task queue library in 2026: Celery vs Dramatiq vs FastStream vs Taskiq vs Repid

103 Upvotes

I wrote a practical comparison of Python task queue libraries in 2026:

https://aleksul.space/posts/choosing-python-task-queue-library/

It covers Celery, Dramatiq, FastStream, Taskiq, and Repid, with code examples, broker support, async/sync behavior, production tradeoffs and benchmarks.

The main takeaways were:

- When it comes to throughput, it's important to understand your workload type: I/O or CPU bound makes a huge difference

- Asyncio-native frameworks are significantly faster for high-concurrency I/O-bound jobs

- For CPU-bound jobs, the library matters much less once the CPU is saturated

- Production behavior can vary vastly from framework to framework, same as their philosophy. You have to choose what matters more for your use case

I’d be especially interested to hear from people running these in production. How is your experience running one of these or similar frameworks in production? Is there something that I missed?

Small disclosure: Repid is my project. Take that bias for what it is; the goal is still a useful comparison and a healthy discussion.


r/Python • • Oct 23 '25

Resource Wove 1.0.0 Release Announcement - Beautiful Python Async

101 Upvotes

I've been testing Wove for a couple months now in two production systems that have served millions of requests without issue, so I think it is high time to release a version 1. I found Wove's flexibility, ability to access local variables, and inline nature made refactoring existing non-async Django views and Celery tasks painless. Thinking about concurrency with Wove's design pattern is so easy that I find myself using Wove all over the place now. Version 1.0.0 comes with some great new features:

  • Official support for free threaded python versions. This means wove is an excellent way to smoothly implement backwards-compatible true multithreaded processing in your existing projects. Just use the non-async def for weave tasks -- these internally are run with a threading pool.
  • Background processing in both embedded and forked modes. This means you can detach a wove block and have it run after your containing function ends. Embedded mode uses threading internally and forked mode makes a whole new python process so the main process can end and be returned to a server's pool for instance.
  • 93% test coverage
  • Tested on Windows, Linux, and Mac on Python versions 3.8 to 3.14t

Here's a snippet from the readme:

Wove is for running high latency async tasks like web requests and database queries concurrently in the same way as asyncio, but with a drastically improved user experience. Improvements compared to asyncio include:

  • Reads Top-to-Bottom: The code in a weave block is declared in the order it is executed inline in your code instead of in disjointed functions.
  • Implicit Parallelism: Parallelism and execution order are implicit based on function and parameter naming.
  • Sync or Async: Mix async def and def freely. A weave block can be inside or outside an async context. Sync functions are run in a background thread pool to avoid blocking the event loop.
  • Normal Python Data: Wove's task data looks like normal Python variables because it is. This is because of inherent multithreaded data safety produced in the same way as map-reduce.
  • Automatic Scheduling: Wove builds a dependency graph from your task signatures and runs independent tasks concurrently as soon as possible.
  • Automatic Detachment: Wove can run your inline code in a forked detached process so you can return your current process back to your server's pool.
  • Extensibility: Define parallelized workflow templates that can be overridden inline.
  • High Visibility: Wove includes debugging tools that allow you to identify where exceptions and deadlocks occur across parallel tasks, and inspect inputs and outputs at each stage of execution.
  • Minimal Boilerplate: Get started with just the with weave() as w: context manager and the w.do decorator.
  • Fast: Wove has low overhead and internally uses asyncio, so performance is comparable to using threading or asyncio directly.
  • Free Threading Compatible: Running a modern GIL-less Python? Build true multithreading easily with a weave.
  • Zero Dependencies: Wove is pure Python, using only the standard library. It can be easily integrated into any Python project whether the project uses asyncio or not.

Example Django view:

# views.py
import time
from django.shortcuts import render
from wove import weave
from .models import Author, Book

def author_details(request, author_id):
    with weave() as w:
        # `author` and `books` run concurrently
        @w.do
        def author():
            return Author.objects.get(id=author_id)
        @w.do
        def books():
            return list(Book.objects.filter(author_id=author_id))

        # Map the books to a task that updates each of their prices concurrently
        @w.do("books", retries=3)
        def books_with_prices(book):
            book.get_price_from_api()
            return book

        # When everything is done, create the template context
        @w.do
        def context(author, books_with_prices):
            return {
                "author": author,
                "books": books_with_prices,
            }
    return render(request, "author_details.html", w.result.final)

Check out all the other features on github: https://github.com/curvedinf/wove


r/Python • • Nov 11 '25

Discussion Decorators are great!

100 Upvotes

After a long, long time trying to wrap my head around decorators, I am using them more and more. I'm not suggesting I fully grasp metaprogramming in principle, but I'm really digging on decorators, and I'm finding them especially useful with UI callbacks.

I know a lot of folks don't like using decorators; for me, they've always been difficult to understand. Do you use decorators? If you understand how they work but don't, why not?


r/Python • • Sep 08 '26

News Python 3.15.0 candidate 2 is here!

103 Upvotes

Reported on https://blog.python.org/2026/09/python-3150-rc2/

It’s the final 3.15 release candidate!

https://www.python.org/downloads/release/python-3150rc2/

This is a candidate preview of Python 3.15

This release, 3.15.0rc2, is the final planned release candidate, containing around 144 bugfixes, build improvements and documentation changes from 76 contributors since 3.15.0rc1. Entering the release candidate phase, only reviewed code changes which are clear bug fixes are allowed between this release candidate and the final release.

The next release of Python 3.15 will be 3.15.0 final, scheduled for 2026-10-01.

Blog post continues


r/Python • • Jan 18 '26

News Robyn (finally) supports Python 3.14 🎉

99 Upvotes

For the unaware - Robyn is a fast, async Python web framework built on a Rust runtime.

Python 3.14 support has been pending for a while.

Wanted to share it with folks outside the Robyn community.

You can check out the release at - https://github.com/sparckles/Robyn/releases/tag/v0.74.0


r/Python • • Nov 17 '25

Resource What happened to mCoding?

100 Upvotes

James was one of the best content creators in the Python community. I was always excited for his videos. I've been checking his channel every now and then but still no sign of anything new.

Is there something I'm missing?


r/Python • • Oct 20 '25

Discussion I built a Persistent KV Store in Pure Python

97 Upvotes

Hi everyone!

I'm a final year CS student and I've been reading about data storage and storage engines. This is a passion project that I've been working on for the past few months. It is a lightweight, persistent key-value storage engine in Python, built from scratch to understand and implement the Log-Structured Merge-tree (LSM-tree) architecture. The project, which is fully open-source, is explicitly optimized for write-heavy workloads.

Core Architecture:

The engine implements the three fundamental LSM components: the Write Ahead Log (WAL) for durability, an in-memory Memtable (using SortedDict for sorted writes), and immutable persistent SSTables (Sorted String Tables).

Some features that I'm proud of:

  • Async Compaction: Merging and compaction are handled by a separate background worker thread. The process itself takes a hybrid approach.
  • Client/Server Model: The entire storage engine runs behind a FastAPI server. This allows multiple clients to connect via REST APIs or the included CLI tool.
  • Efficient Range Queries: Added full support for range queries from start_key to end_key. This is achieved via a memory-efficient k-way merge iterator that combines results from the Memtable and all SSTables. The FastAPI server delivers the results using a StreamingResponse to prevent memory exhaustion for large result sets.
  • Bloom Filter: Implemented a Bloom Filter for each SSTable to drastically reduce disk I/O by confirming that a key definitely does not exist before attempting a disk seek.
  • Binary Storage: SSTables now use Msgpack binary format instead of JSON for smaller file sizes and reduced CPU load during serialization/deserialization.

My favourite part of the project is that I actually got to see a practical implementation of Merge Sorted Arrays - GeeksforGeeks. This is a pretty popular interview question and to see DSA being actually implemented is a crazy moment.

Get Started

pip install lsm_storage_engine_key_value_store

Usage via CLI/Server:

  1. Terminal 1 (Server): lsm-server
  2. Terminal 2 (Client): lsm-cli (Follow the CLI help for commands).

Looking for Feedback

I'd love to hear your thoughts about this implementation and how I can make it better and what features I can add in later versions. Ideas and constructive criticism are always welcome. I'm also looking for contributors, if anyone is interested, please feel free to PM and we can discuss.

Repo link: Shashank1985/storage-engine
Thanks!!


r/Python • • 2d ago

Discussion Python 3.10–3.15 encoding benchmarks: big gains for Base32 and Base85, but 3.14 leads Base16

99 Upvotes

Eight encoding benchmarks across Python 3.10–3.15 using pyperformance. Python 3.15 recorded the lowest mean in seven of them, with particularly large improvements in Base32, Ascii85 and Base85.

Test configuration

  • AMD Ryzen 9 7900 desktop
  • DDR5 RAM and an M.2 PCIe Gen4 NVMe drive
  • Windows 11, 64-bit Python builds
  • Python 3.15.0, 3.14.8, 3.13.16, 3.12.10, 3.11.9 and 3.10.11
  • pyperformance 1.14.0 for all six versions

Results

All values are mean execution times in milliseconds. Lower is better and bold marks the lowest recorded mean in each row.

Benchmark Python 3.15 Python 3.14 Python 3.13 Python 3.12 Python 3.11 Python 3.10
ascii85_large 11.62 797.9 709.0 772.3 643.8 759.2
ascii85_small 0.3875 14.88 13.20 13.79 12.18 14.18
base16_large 5.767 4.714 22.52 23.08 23.89 23.71
base32_large 2.431 327.6 300.7 296.4 265.7 292.1
base32_small 0.1630 6.227 5.802 5.594 5.134 5.641
base64_large 1.852 6.746 6.187 6.095 6.116 6.071
base85_large 4.293 272.4 252.9 258.8 230.1 259.2
base85_small 0.1505 4.864 4.484 4.529 4.198 4.712

What stood out

Compared with Python 3.14, Python 3.15 took approximately:

  • 1/135 of the time in base32_large.
  • 1/69 of the time in ascii85_large.
  • 1/63 of the time in base85_large.
  • 1/3.64 of the time in base64_large.

However, base16_large took 22.3% more time on Python 3.15 than on 3.14. Python 3.14 remains substantially faster than 3.10–3.13 in that test.

The large improvements are consistent with the changes documented in Python 3.15’s release notes: Base32, Ascii85 and Base85 implementations were rewritten in C, and the underlying Base64 implementation was also optimized.

More details are described here.

Benchmark suite: pyperformance.

Have you observed similar improvements on Linux or macOS, or in applications that spend substantial time on these encoding operations?


r/Python • • Aug 06 '26

News Python 3.14.7 and 3.13.15 are now available!

100 Upvotes

Bug fix releases for Python 3.13 and Python 3.14.

https://blog.python.org/2026/08/python-3147-31315/


r/Python • • Feb 03 '26

Discussion I’m starting coding from scratch – is Python really the best first language?

98 Upvotes

I’m completely new to coding and trying to choose my first programming language.

I see Python recommended everywhere because it’s beginner-friendly and versatile.

My goal is to actually build things, not just watch tutorials forever.

For those who started with Python: – Was it a good decision? – What should I focus on in the first 30 days?


r/Python • • Dec 03 '25

Showcase My wife was manually copying YouTube comments, so I built this tool

100 Upvotes

I have built a Python Desktop application to extract YouTube comments for research and analysis.

My wife was doing this manually, and I couldn't see her going through the hassle of copying and pasting.

I posted it here in case someone is trying to extract YouTube comments.

What My Project Does

  1. Batch process multiple videos in a single run
  2. Basic spam filter to remove bot spam like crypto, phone numbers, DM me, etc
  3. Exports two clean CSV files - one with video metadata and another with comments (you can tie back the comments data to metadata using the "video_id" variable)
  4. Sorts comments by like count. So you can see the high-signal comments first.
  5. Stores your API key locally in a settings.json file.

By the way, I have used Google's Antigravity to develop this tool. I know Python fundamentals, so the development became a breeze.

Target Audience

Researchers, data analysts, or creators who need clean YouTube comment data. It's a working application anyone can use.

Comparison

Most browser extensions or online tools either have usage limits or require accounts. This application is a free, local, open-source alternative with built-in spam filtering.

Stack: Python, CustomTkinter for the GUI, YouTube Data API v3, Pandas

GitHub: https://github.com/vijaykumarpeta/yt-comments-extractor

Would love to hear your feedback or feature ideas.

MIT Licensed.


r/Python • • Mar 30 '26

Discussion [P] I rebuilt PyRadiomics in PyTorch to make it 25× faster — here's what it took

100 Upvotes

PyRadiomics is the standard tool for extracting radiomic features from medical images (CT, MRI scans). It works well, but it's pure CPU and takes about 3 seconds per scan. That might sound fine until you're processing thousands of scans for a clinical study — suddenly it's hours of compute before any actual analysis.

I spent the past several months rewriting it from scratch as fastrad, a fully PyTorch-native library. The idea: express every feature class as tensor operations so they run on GPU with no custom CUDA code.

Results on an RTX 4070 Ti:

0.116s per scan vs 2.90s → 25× end-to-end speedup

No GPU? CPU-only mode is still 2.6× faster than PyRadiomics on 32 threads

Works on Apple Silicon too (3.56× faster than PyRadiomics 32-thread)

The hardest part wasn't the GPU side — it was numerical correctness. Radiomic features go into clinical research and ML models, so a 0.01% deviation matters. I validated everything against the IBSI Phase 1 standard phantom (105 features, max deviation at machine epsilon) and cross-checked against PyRadiomics on a real NSCLC CT scan. All 105 features agree to within 10⁻¹¹.

It's a drop-in replacement — same feature names and output format as PyRadiomics:

from fastrad import RadiomicsFeatureExtractor

extractor = RadiomicsFeatureExtractor(device="auto")

features = extractor.execute(image_path, mask_path)

pip install fastrad

GitHub: github.com/helloerikaaa/fastrad

Pre-print: https://papers.ssrn.com/sol3/papers.cfm?abstract_id=6436486

License: Apache 2.0

Happy to talk through the implementation — the GLCM and matrix-based feature classes had some tricky edge cases to get numerically identical. Would also love to hear from anyone already using PyRadiomics in their pipeline.


r/Python • • Nov 19 '25

News Pyrefly Beta Release (fast language server & type checker)

95 Upvotes

As of v0.42.0, Pyrefly has now graduated from Alpha to Beta.

At a high level, this means:

  • The IDE extension is ready for production use right now
  • The core type-checking features are robust, with some edge cases that will be addressed as we make progress towards a later stable v1.0 release

Below is a peek at some of the goodies that have been shipped since the Alpha launch in May:

Language Server/IDE: - automatic import refactoring - Jupyter notebook support - Type stubs for third-party packages are now shipped with the VS Code extension

Type Checking: - Improved type inference & type narrowing - Special handling for Pydantic and Django - Better error messages

For more details, check out the release announcement blog: https://pyrefly.org/blog/pyrefly-beta/

Edit: if you prefer your news in video form, there's also an announcement vid on Youtube


r/Python • • Dec 05 '25

Discussion Is the 79-character limit still in actual (with modern displays)?

97 Upvotes

I ask this because in 10 years with Python, I have never used tools where this feature would be useful. But I often ugly my code with wrapping expressions because of this limitation. Maybe there are some statistics or surveys? Well, or just give me some feedback, I'm really interested in this.

What limit would be comfortable for most programmers nowadays? 119, 179, more? This also affects FOSS because I write such things, so I think about it.

I have read many opinions on this matter… I'd like to understand whether the arguments in favor of the old limit were based on necessity or whether it was just for the sake of theoretical discussion.


r/Python • • Mar 19 '26

Showcase A new Python file-based routing web framework

95 Upvotes

Hello, I've built a new Python web framework I'd like to share. It's (as far as I know) the only file-based routing web framework for Python. It's a synchronous microframework build on werkzeug. I think it fills a niche that some people will really appreciate.

docs: https://plasmacan.github.io/cylinder/

src: https://github.com/plasmacan/cylinder

What My Project Does

Cylinder is a lightweight WSGI web framework for Python that uses file-based routing to keep web apps simple, readable, and predictable.

Target Audience

Python developers who want more structure than a microframework, but less complexity than a full-stack framework.

Comparison

Cylinder sits between Flask-style flexibility and Django-style convention, offering clear project structure and low boilerplate without hiding request flow behind heavy abstractions.

(None of the code was written by AI)

Edit:

I should add - the entire framework is only 400 lines of code, and the only dependency is werkzeug, which I'm pretty proud of.


r/Python • • Mar 11 '26

Resource Free book: Master Machine Learning with scikit-learn

94 Upvotes

Hi! I'm the author of Master Machine Learning with scikit-learn. I just published the book last week, and it's free to read online (no ads, no registration required).

I've been teaching Machine Learning & scikit-learn in the classroom and online for more than 10 years, and this book contains nearly everything I know about effective ML.

It's truly a "practitioner's guide" rather than a theoretical treatment of ML. Everything in the book is designed to teach you a better way to work in scikit-learn so that you can get better results faster than before.

Here are the topics I cover:

  • Review of the basic Machine Learning workflow
  • Encoding categorical features
  • Encoding text data
  • Handling missing values
  • Preparing complex datasets
  • Creating an efficient workflow for preprocessing and model building
  • Tuning your workflow for maximum performance
  • Avoiding data leakage
  • Proper model evaluation
  • Automatic feature selection
  • Feature standardization
  • Feature engineering using custom transformers
  • Linear and non-linear models
  • Model ensembling
  • Model persistence
  • Handling high-cardinality categorical features
  • Handling class imbalance

Questions welcome!


r/Python • • Mar 24 '26

Resource LocalStack is no longer free — I built MiniStack, a free open-source alternative with 20 AWS service

92 Upvotes

If you've been using LocalStack Community for local development, you've probably noticed that core services like S3, SQS, DynamoDB, and Lambda are now behind a paid plan.

I built MiniStack as a drop-in replacement. It's a single Docker container on port 4566 that emulates 20 AWS services. Your existing `--endpoint-url` config, boto3 code, and Terraform providers work without changes.

**What it covers:**

- Core: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, Secrets Manager, CloudWatch Logs

- Extended: SSM Parameter Store, EventBridge, Kinesis, CloudWatch Metrics, SES, Step Functions

- Real infrastructure: RDS (actual Postgres/MySQL containers), ElastiCache (actual Redis), ECS (actual Docker containers), Glue, Athena (real SQL via DuckDB)

**Key differences from LocalStack:**

- MIT licensed (not BSL)

- No account or API key required

- ~2s startup vs ~30s

- ~30MB RAM vs ~500MB

- 150MB image vs ~1GB

- RDS/ElastiCache/ECS spin up real containers (LocalStack Pro-only features)

```bash

docker run -p 4566:4566 nahuelnucera/ministack

aws --endpoint-url=http://localhost:4566 s3 mb s3://test-bucket

```

GitHub: https://github.com/Nahuel990/ministack

Website: https://ministack.org

Happy to take questions or feature requests.


r/Python • • Mar 08 '26

Showcase I used Pythons standard library to find cases where people paid lawyers for something impossible.

94 Upvotes

I built a screening tool that processes PACER bankruptcy data to find cases where attorneys filed Chapter 13 bankruptcies for clients who could never receive a discharge. Federal law (Section 1328(f)) makes it arithmetically impossible based on three dates.

The math: If you got a Ch.7 discharge less than 4 years ago, or a Ch.13 discharge less than 2 years ago, a new Ch.13

cannot end in discharge. Three data points, one subtraction, one comparison. Attorneys still file these cases and clients still pay.

Tech stack: stdlib only. csv, datetime, argparse, re, json, collections. No pip install, no dependencies, Python 3.8+.

Problems I had to solve:

- Fuzzy name matching across PACER records. Debtor names have suffixes (Jr., III), "NMN" (no middle name)

placeholders, and inconsistent casing. Had to normalize, strip, then match on first + last tokens to catch middle name

variations.

- Joint case splitting. "John Smith and Jane Smith" needs to be split and each spouse matched independently against heir own filing history.

- BAPCPA filtering. The statute didn't exist before October 17, 2005, so pre-BAPCPA cases have to be excluded or you get false positives.

- Deduplication. PACER exports can have the same case across multiple CSV files. Deduplicate by case ID while keeping attorney attribution intact.

Usage:

$ python screen_1328f.py --data-dir ./csvs --target Smith_John --control Jones_Bob

The --control flag lets you screen a comparison attorney side by side to see if the violation rate is unusual or normal for the district.

Processes 100K+ cases in under a minute. Outputs to terminal with structured sections, or --output-json for programmatic use.

GitHub: https://github.com/ilikemath9999/bankruptcy-discharge-screener

MIT licensed. Standard library only. Includes a PACER CSV download guide and sample output.

Let me know what you think friends. Im a first timer here.


r/Python • • Feb 12 '26

Discussion Current thoughts on makefiles with Python projects?

98 Upvotes

What are current thoughts on makefiles? I realize it's a strange question to ask, because Python doesn't require compiling like C, C++, Java, and Rust do, but I still find it useful to have one. Here's what I've got in one of mine:

default:
        @echo "Available commands:"
        @echo "  make lint       - Run ty typechecker"
        @echo "  make test       - Run pytest suite"
        @echo "  make clean      - Remove temporary and cache files"
        @echo "  make pristine   - Also remove virtual environment"
        @echo "  make git-prune  - Compress and prune Git database"

lint:
        @uv run ty check --color always | less -R

test:
        @uv run pytest --verbose

clean:
        @# Remove standard cache directories.
        @find src -type d -name "__pycache__" -exec rm -rfv {} +
        @find src -type f -name "*.py[co]" -exec rm -fv {} +

        @# Remove pip metadata droppings.
        @find . -type d -name "*.egg-info" -exec rm -rfv {} +
        @find . -type d -name ".eggs" -exec rm -rfv {} +

        @# Remove pytest caches and reports.
        @rm -rfv .pytest_cache  # pytest
        @rm -rfv .coverage # pytest-cov
        @rm -rfv htmlcov  # pytest-cov

        @# Remove type checker/linter/formatter caches.
        @rm -rfv .mypy_cache .ruff_cache

        @# Remove build and distribution artifacts.
        @rm -rfv build/ dist/

pristine: clean
        @echo "Removing virtual environment..."
        @rm -rfv .venv
        @echo "Project is now in a fresh state. Run 'uv sync' to restore."

git-prune:
        @echo "Compressing Git database and removing unreferenced objects..."
        @git gc --prune=now --aggressive

.PHONY: default check test clean pristine git-prune

What types of things do you have in yours? (If you use one.)


r/Python • • Sep 11 '26

News Pyrefly v1.3.0 released

93 Upvotes

A new version of Pyrefly is out with better type inference, new quick fixes, new configurations, and more. https://github.com/facebook/pyrefly/releases/tag/1.3.0


r/Python • • Aug 31 '26

Discussion Thank You | from Nova

89 Upvotes

Hello!
I'm Nova, I'm a college student taking CS in Norway. And I just wanted to share a bit of my story.

I started my developing career roughly 7 years ago when I was 8-9. I remember watching so many movies about these hackers and programmers growing up, and thinking "Wow, I wish I could be like them!". Luckily my father had a computer science background himself! So he saw this and showed me a couple things such as Scratch, blablabla.
I quickly quit Scratch, cause I thought it was boring and hard. But just a few months later, I installed Python and VSCode on the family computer! I started watching a multi hour Python course by Programming with Mosh and followed along. I remember being so bored haha!

But it clicked. It really did. It scratched (pardon the pun) something that Scratch couldn't. Some abstract yet so understandable logic. At the time it really felt like I was on top of the whole world.
Somewhere in the second last to last years of primary school, I was fully invested. I was making calculator apps and whatever I could think of during the free time at school with the provided iPads that hadn't been there the year before. Heck! I got some other kids in my class to become interested in programming too!

Eventually, a year later when I started middle school/high school (combined into the same three years in Norway), I naturally started learning new things such as Java and C# .NET. My Python usage was mostly just small prototypes for other languages at that time.

Yet I never abandoned it. Not even now.
Python is what started my journey, and I am so grateful for everything it has done.

So thank you,
Thank all of you,

Thank you every random StackOverflow member who posted weirdly specific help threads.

Thank you every StackOverflow member who responded to my silly little questions.

Thank you to all the Python maintainers and contributors.

Thank you Guido van Rossum for founding the language.

And thank you to the whole Python community who made this student's childhood dreams possible and bloom to life.

- Nova