r/Python • • Mar 04 '26

News https://www.youtube.com/watch?v=qKkyBhXIJJU

0 Upvotes

Just wanted to share(no affiliation) about live Python Unplugged on PyTv right now: https://www.youtube.com/watch?v=qKkyBhXIJJU

Interesting discussion about community mainly but development- focused for the Python community :)


r/Python • • Mar 04 '26

Showcase VSCode uv Extension: uv Auto venv (PEP 723 & pyproject.toml)

9 Upvotes

I created yet another VSCode extension: uv Auto venv
Find it here:
VSCode Marketplace & GitHub

What My Project Does
Automatically activates uv Python environments the moment you switch tabs in VS Code.
It works with standard projects AND scripts with PEP 723 inline metadata.

It doesn't create venv's for you, because I like to manage them explicitly myself using uv in the terminal. I just want the linting to work when i switch between projects and scripts.

Target Audience
Comes in handy for repos with multiple projects/scripts, where VSCode won't pick up the venv automatically.

Comparison
I couldn't find any extensions that work for both projects with pyproject.toml and PEP 723 inline metadata, so I created this one.

Call for Logo Design:
The logo is ugly, I created it with AI and don't like it. The repo is open for design contributions, if you want to contribute a new one, let me know!


r/Python • • Mar 04 '26

Showcase Made a networking library for multiplayer games -- pump() once per frame and forget about sockets

30 Upvotes

TL;DR: I built repod, a networking library for Python games (Pygame, Raylib, Arcade). No async/await boilerplate in your game loop—just send/receive dicts and call pump() once per frame.

repod is a high-level networking library designed for real-time multiplayer games. It abstracts away the complexity of asyncio and sockets, allowing developers to handle network events through simple class methods.

Instead of managing buffers or coroutines, you simply:

  1. Subclass a Channel (server) or ConnectionListener (client).
  2. Write methods starting with Network_ (e.g., Network_move).
  3. Call pump() once per frame in your main loop to dispatch all pending messages.

It uses msgpack for fast serialization and length-prefix framing to ensure data integrity.

Target Audience

This is currently meant for indie developers, hobbyists, and game jam participants.

  • Current Status: Early stages (v0.1.2), but stable enough for projects.
  • Goal: It's perfect for those who want to add multiplayer to a Pygame/Raylib project without restructuring their entire codebase around an asynchronous architecture.

Comparison

Compared to other solutions:

  • vs. Raw Sockets/Asyncio: Much higher level. No need to handle partial packets, byte encoding, or event loop management.
  • vs. PodSixNet: It’s essentially a modern spiritual successor. While PodSixNet is broken on Python 3.12+ (due to the removal of asyncore), repod uses a modern asyncio backend while keeping the same easy-to-use API.
  • vs. Twisted/Autobahn: Much lighter. It doesn't force a specific framework on you; it just sits inside your existing while True loop.

Quick Example (Server)

Python

from repod import Channel, Server

class GameChannel(Channel):
    def Network_chat(self, data: dict) -> None:
        # Broadcasts: {"action": "chat", "msg": "hello"}
        self.server.send_to_all({"action": "chat", "msg": data["msg"]})

class GameServer(Server):
    channel_class = GameChannel

GameServer(host="0.0.0.0", port=5071).launch()

Links & Info

I've included examples in the repo for a chat room, a shared whiteboard (pygame-ce), and Pong with server-authoritative physics. I'd love to hear your thoughts or what features you'd like to see next!


r/Python • • Mar 04 '26

News Google just open-sourced cel-expr-python (CEL) — safe, typed expressions for Python (C++ wrapper)

90 Upvotes

Google Open Source Blog posted a new release today (Mar 3, 2026): cel-expr-python, a native Python API for compiling + evaluating CEL (Common Expression Language) expressions.

Repo: https://github.com/cel-expr/cel-python

Announcement: https://opensource.googleblog.com/2026/03/announcing-cel-expr-python-the-common-expression-language-in-python-now-open-source.html

Codelab: https://github.com/cel-expr/cel-python/blob/main/codelab/index.lab.md

Why I’m interested:

- It’s the official CEL team’s Python wrapper over the production CEL C++ implementation (so semantics should match what other CEL runtimes do).

- It’s designed for “compile once, eval many” workflows with type-checking during compile (so you can validate expressions up front instead of `eval()`-ing arbitrary Python).

- It supports extensions and can serialize compiled expressions.

Quick start (from the blog/docs; blog snippet had a small typo so I’m writing the corrected version here):

pip install cel-expr-python

from cel_expr_python import cel

env = cel.NewEnv(variables={"who": cel.Type.STRING})

expr = env.compile("'Hello, ' + who + '!'")

print(expr.eval(data={"who": "World"}).value()) # Hello, World!

Doc snippet: serialize + reuse compiled expressions

env = cel.NewEnv(variables={"x": cel.Type.INT, "y": cel.Type.INT})

expr = env.compile("x + y > 10")

blob = expr.serialize()

expr2 = env.deserialize(blob)

print(expr2.eval(data={"x": 7, "y": 4}).value()) # True

Doc snippet: custom function extension in Python

def my_func_impl(x):

return x + 1

my_ext = cel.CelExtension("my_extension", [cel.FunctionDecl("my_func", [cel.Overload("my_func_int", cel.Type.INT[cel.Type.INT], impl=my_func_impl)])])

env = cel.NewEnv(extensions=[my_ext])

expr = env.compile("my_func(41)")

print(expr.eval().value()) # 42

Side note / parallel that made me click on this:

I was just reading the r/Python thread on PEP 827 (type manipulation + expanding the type expression grammar):

https://www.reddit.com/r/Python/comments/1rimuu7/pep_827_type_manipulation_has_just_been_published/

Questions if there are any folks who’ve used CEL before:

- Where has CEL worked well (policy engines, validation, feature flags, filtering, etc.)?

- How does this compare to rolling your own AST-based evaluator / JsonLogic / JMESPath for real-world apps?

- Any gotchas with Python integration, perf, or packaging (looks like Linux + py3.11+ right now)?


r/Python • • Mar 04 '26

Showcase I built a cryptographic commitment platform with FastAPI and Bitcoin timestamps (MIT licensed)

0 Upvotes

PSI-COMMIT is a web platform (and Python backend) that lets you cryptographically seal a prediction, hypothesis, or decision — then reveal it later with mathematical proof you didn't change it. The backend is built entirely in Python with FastAPI and handles commitment storage, verification, Bitcoin timestamping via OpenTimestamps, and user authentication through Supabase.

All cryptographic operations run client-side via the Web Crypto API, so the server never sees your secret key. The Python backend handles:

  • Commitment storage and retrieval via FastAPI endpoints
  • HMAC-SHA256 verification on reveal (constant-time comparison)
  • OpenTimestamps submission and polling for Bitcoin block confirmation
  • JWT authentication and admin-protected routes
  • OTS receipt management and binary .ots file serving

GitHub: https://github.com/RayanOgh/psi-commit Live: https://psicommit.com

Target Audience

Anyone who needs to prove they said something before an outcome — forecasters, researchers pre-registering hypotheses, teams logging strategic decisions, or anyone tired of "I told you so" without proof. It's a working production tool with real users, not a toy project.

Comparison

Unlike using GPG signatures (which require keypair management and aren't designed for commit-reveal schemes), PSI-COMMIT is purpose-built for timestamped commitments. Compared to hashing a file and posting it on Twitter, PSI-COMMIT adds domain separation to prevent cross-context replay, a 32-byte nonce per commitment, Bitcoin anchoring via OpenTimestamps for independent timestamp verification, and a public wall where revealed predictions are displayed with full cryptographic proof anyone can verify. The closest alternative is manually running openssl dgst and submitting to OTS yourself — this wraps that workflow into a clean web interface with user accounts and a verification UI.


r/Python • • Mar 04 '26

News I updated Dracula-AI based on some advice and criticism. You can see here what changed.

0 Upvotes

Firstly, hello everyone. I'm an 18-year-old Computer Engineering student in Turkey.

I wanted to develop a Python library because I always enjoy learning new things and want to improve my skills, so I started building it.

A little while ago, I shared Dracula-AI, a lightweight Python wrapper I built for the Google Gemini API. The response was awesome, but you guys gave me some incredibly valuable, technical criticism:

  1. "Saving conversation history in a JSON file is going to cause massive memory bloat."
  2. "Why is PyQt6 a forced dependency if I just want to run this on a server or a Discord bot?"
  3. "No exponential backoff/retry mechanism? One 503 error from Google and the whole app crashes."

I took every single piece of feedback seriously. I went back to the drawing board, and I tried to make it more stable.

Today, I’m excited to release Dracula v0.8.0.

What’s New?

  • SQLite Memory Engine: I gave up on using JSON and tried to build a memory system with SQLite. Conversation history and usage stats are now natively handled via a robust SQLite database (sqlite3 for sync, aiosqlite for async). It scales perfectly even for massive chat histories.
  • Smart Auto-Retry: Dracula now features an under-the-hood exponential backoff mechanism. It automatically catches temporary network drops, 429 rate limits, and 503 errors, retrying smoothly without crashing your app.
  • Zero UI Bloat: I split the dependencies!

    • If you're building a backend, FastAPI, or a Discord bot: pip install dracula-ai .
    • If you want the built-in PyQt6 desktop app: pip install dracula-ai[ui].
  • True Async Streaming: Fixed a generator bug so streaming now works natively without blocking the asyncio event loop.

Quick Example:

import os
from dracula import Dracula
from dotenv import load_dotenv

load_dotenv()

# Automatically creates SQLite db and handles retries under the hood
with Dracula(api_key=os.getenv("GEMINI_API_KEY")) as ai:
    response = ai.chat("What's the meaning of life?")
    print(response)
    
    # You can also use built-in tools, system prompts, and personas!

Building this has been a massive learning curve for me. Your feedback pushed me to learn about database migrations, optional package dependencies, and proper async architectures.

I’d love for you guys to check out the new version and tear it apart again so I can keep improving!

Let me know what you think, I need your feedback :)

By the way, if you want to review the code, you can visit my GitHub repo. Also, if you want to develop projects with Dracula, you can visit its PyPi page.


r/Python • • Mar 03 '26

Showcase formualizer: an Arrow-backed spreadsheet engine - 320+ functions, incremental recalc, PyO3 + Rust

72 Upvotes

pip install formualizer

import formualizer as fz

# Recalculate every formula in an xlsx and write it back - one call
fz.recalculate_file("model.xlsx", output="recalculated.xlsx")

# Or drive it programmatically
wb = fz.load_workbook("model.xlsx")
wb.set_value("Assumptions", 3, 2, 0.08)  # swap in a new interest rate
wb.evaluate_all()

print(wb.evaluate_cell("Summary", 5, 3))  # =IRR(...)
print(wb.evaluate_cell("Summary", 6, 3))  # =NPV(...)
print(wb.evaluate_cell("Summary", 7, 3))  # =PMT(...)

GitHub: https://github.com/psu3d0/formualizer Docs: https://www.formualizer.dev


Why this exists

Python's Excel formula situation sucks:

  • openpyxl reads and writes .xlsx perfectly, evaluates zero formulas. Cells with =SUM(A1:A10) return None unless Excel already cached the values when someone last saved the file.
  • xlcalc actually evaluates, but covers around 50 functions. XLOOKUP, SUMIFS with multiple criteria, IRR, XIRR, dynamic arrays (FILTER, UNIQUE, SORT), etc don't exist.
  • xlwings works if Excel is installed on the machine. Useless in Docker or on Linux.

The standard workaround - pre-calculate in Excel, save cached values, read with openpyxl - falls apart when someone changes the model, or you need to evaluate the same workbook across thousands of different inputs. Or even just need to evaluate real workbooks of non-trivial size.

formualizer is a Rust formula engine with PyO3 bindings. No Excel. No COM. Runs anywhere Python runs.


Bonus: register Python functions as Excel formulas

def risk_score(grid):
    flat = [v for row in grid for v in row]
    return sum(v ** 2 for v in flat) / len(flat)

wb.register_function("RISK_SCORE", risk_score, min_args=1, max_args=1)
wb.set_formula("Sheet1", 5, 1, "=RISK_SCORE(A1:D100)")

result = wb.evaluate_cell("Sheet1", 5, 1)

Your callback participates in the dependency graph like any built-in - change a cell in A1:D100 and it recalculates on the next evaluate_all().


Comparison

LibraryEvaluatesFunctionsDep. graphWrite xlsxNo ExcelLicense
formualizer✅320+✅ incremental✅✅MIT / Apache-2.0
xlcalc✅~50partial❌✅MIT
openpyxl❌—❌✅✅MIT
xlwings✅~400*❌✅❌BSD

Formal benchmarks are in progress. Rust core, incremental dependency graph (only affected cells recalculate on edits), MIT/Apache-2.0.

This library is fast.


What My Project Does

Python library for evaluating Excel formulas without Excel installed. Rust core via PyO3. 320+ Excel-compatible functions, .xlsx read/write, incremental dependency graph, custom Python formula callbacks, deterministic mode for reproducible evaluation. MIT/Apache-2.0.

Target Audience

Data engineers pulling business logic out of Excel workbooks, fintech/insurance teams running server-side formula evaluation (pricing, amortization, risk), SaaS builders who need spreadsheet logic without a server-side Excel dependency.


r/Python • • Mar 03 '26

Showcase ༄ streamable - sync/async iterable streams for Python

30 Upvotes

https://github.com/ebonnal/streamable

What my project does

A stream[T] wraps any Iterable[T] or AsyncIterable[T] with a lazy fluent interface covering concurrency, batching, buffering, rate limiting, progress observation, and error handling.

Chain lazy operations:

import logging
from datetime import timedelta
import httpx
from httpx import Response, HTTPStatusError
from streamable import stream

pokemons: stream[str] = (
    stream(range(10))
    .map(lambda i: f"https://pokeapi.co/api/v2/pokemon-species/{i}")
    .throttle(5, per=timedelta(seconds=1))
    .map(httpx.get, concurrency=2)
    .do(Response.raise_for_status)
    .catch(HTTPStatusError, do=logging.warning)
    .map(lambda poke: poke.json()["name"])
)

Consume it (sync or async):

>>> list(pokemons)
['bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise']

>>> [pokemon async for pokemon in pokemons]
['bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise']

Target Audience

If you find yourself writing verbose iterable plumbing, streamable will probably help you keep your code expressive, concise, and memory-efficient.

  • You may need advanced behaviors like time-windowed grouping by key, concurrent flattening, periodic observation of the iteration progress, buffering (decoupling upstream production rate from downstream consumption rate), etc.
  • You may want a unified interface for sync and async behaviors, e.g. to switch seamlessly between httpx.Client.get and httpx.AsyncClient.get in your .map (or anywhere else), consume the stream as a sync or as an async iterable, from sync or async context.
  • You may simply want to chain .maps and .filters without overhead vs builtins.map and builtins.filter.

Comparison

Among similar libraries, streamable's proposal is an interface that is:

  • targeting I/O intensive use cases: a minimalist set of a dozen expressive operations particularly elegant to tackle ETL use cases.
  • unifying sync and async: Create streams that are both Iterable and AsyncIterable, with operations adapting their behavior to the type of iteration and accepting sync and async functions.

The README gives a complete tour of the library, and I’m also happy to answer any questions you may have in the comments.

About 18 months ago I presented here the 1.0.0.
I'm glad to be back to present this matured 2.0.0 thanks to your feedback and contributions!


r/Python • • Mar 03 '26

Showcase PDF Oxide -- Fast PDF library for Python with engine in Rust (0.8ms mean, MIT/Apache license)

203 Upvotes

pdf_oxide is a PDF library for text extraction, markdown conversion, PDF creation, OCR. Written in Rust, Python bindings via PyO3. MIT licensed.

    pip install pdf_oxide

    from pdf_oxide import PdfDocument
    doc = PdfDocument("paper.pdf")
    text = doc.extract_text(0)

GitHub: https://github.com/yfedoseev/pdf_oxide
Docs: https://oxide.fyi

Why this exists: I needed fast text extraction with a permissive license. PyMuPDF is fast but AGPL, rules it out for a lot of commercial work. pypdf is MIT but 15x slower and chokes on ~2% of files. pdfplumber is great at tables but not at batch speed.

So I read the PDF spec cover to cover (~1,000 pages) and wrote my own. First version took 23ms per file. Profiled it, found an O(n2) page tree traversal -- a 10,000 page PDF took 55 seconds. Cached it into a HashMap, got it down to 332ms. Kept profiling, kept fixing. Now it's at 0.8ms mean on 3,830 real PDFs.

Numbers on that corpus (veraPDF, Mozilla pdf.js, DARPA SafeDocs):

LibraryMeanp99Pass RateLicense
pdf_oxide0.8ms9ms100%MIT
PyMuPDF4.6ms28ms99.3%AGPL-3.0
pypdfium24.1ms42ms99.2%Apache-2.0
pdftext7.3ms82ms99.0%GPL-3.0
pypdf12.1ms97ms98.4%BSD-3
pdfminer16.8ms124ms98.8%MIT
pdfplumber23.2ms189ms98.8%MIT
markitdown108.8ms378ms98.6%MIT

Give it a try, let me know what breaks.

What My Project Does

Rust PDF library with Python bindings. Extracts text, converts to markdown and HTML, creates PDFs, handles encrypted files, built-in OCR. MIT licensed.

Target Audience

Anyone who needs to pull text out of PDFs in Python without AGPL restrictions, or needs speed for batch processing.

Comparison

5-30x faster than other text extraction libraries on a 3,830-PDF corpus. PyMuPDF is more mature but AGPL. pdfplumber is better at tables. pdf_oxide is faster with a permissive license.


r/Python • • Mar 03 '26

Showcase Building Post4U - a self-hosted social media scheduler with FastAPI + APScheduler

1 Upvotes

Been working on Post4U for a couple of weeks, an open source scheduler that cross-posts to X, Telegram, Discord and Reddit from a single REST API call.

What My Project Does

Post4U exposes a REST API where you send your content, a list of platforms, and an optional scheduled time. It handles the rest — posting to each platform at the right time, tracking per-platform success or failure, and persisting scheduled jobs across container restarts.

Target Audience

Developers and technically inclined people who want to manage their own social posting workflow without handing API keys to a third party. Not trying to replace Buffer for non-technical users - this is for people comfortable with Docker and a .env file. Toy project for now, with the goal of making it production-ready.

Comparison

Most schedulers (Buffer, Hootsuite, Typefully) are SaaS, your credentials live on their servers and you pay monthly. The self-hosted alternatives I found were either abandoned, overly complex, or locked to one platform. Post4U is intentionally minimal — one docker-compose up, your keys stay on your machine, codebase small enough to actually read and modify.

The backend decision I keep second-guessing is APScheduler with a MongoDB job store instead of Celery + Redis. MongoDB was already there for post history so it felt natural - jobs persist across restarts with zero extra infrastructure. Curious if anyone here has run APScheduler in production and hit issues at scale.

Started the Reflex frontend today. Writing a web UI in pure Python is a genuinely interesting experience, built-in components are good for scaffolding fast but the moment you need full layout control you have to drop into rx.html. State management is cleaner than expected though, extend rx.State, define your vars, changes auto re-render dependent components. Very React-like without leaving Python.

Landing page done, dashboard next.

Would love feedback on the problem itself, the APScheduler decision, or feature suggestions.

GitHub: https://github.com/ShadowSlayer03/Post4U-Schedule-Social-Media-Posts


r/Python • • Mar 03 '26

Discussion Anyone in here in the UAS Flight Test Engineer industry using python?

8 Upvotes

Specifically using python to read & analyze flight data logs and even for testing automations.

I’m looking to expand my uas experience and grow into a FTE role. Most roles want experience using python, CPP, etc. I’m pretty new to python. Wanted to know if anyone can give some advice.


r/Python • • Mar 03 '26

Showcase cMCP v0.4.0 released!

0 Upvotes

What My Project Does

cMCP is a command-line utility for interacting with MCP servers - basically curl for MCP.

New in v0.4.0: mcp.json configuration support! 🎉

Installation

pip install cmcp

Quickstart

Create .cmcp/mcp.json:

{
  "mcpServers": { 
    "my-server": { 
      "command": "python",
      "args": ["server.py"]
    } 
  } 
}

Use it:

cmcp :my-server tools/list
cmcp :my-server tools/call name=add arguments:='{"a": 1, "b": 2}'

Compatible with Cursor, Claude Code, and FastMCP format.

GitHub: https://github.com/RussellLuo/cmcp


r/Python • • Mar 03 '26

Showcase scientific_pydantic: Pydantic adapters for common scientific data types

34 Upvotes

Code: https://github.com/psalvaggio/scientific_pydantic

Docs: https://psalvaggio.github.io/scientific_pydantic/latest/

What My Project Does

This project integrates a number of common scientific data types into pydantic. It uses the Annotated pattern for integrating third-party types with adapter objects. For example:

import typing as ty  
import astropy.units as u  
import pydantic  
from scientific_pydantic.astropy.units import QuantityAdapter

class Points(pydantic.BaseModel):  
points: ty.Annotated[u.Quantity, QuantityAdapter(u.m, shape=(None, 3), ge=0)]  

would define a model with a field that is an N x 3 array of points with non-negative XYZ in spatial units equivalent to meters.

No need for arbitrary_types_allowed=True and with the normal pydantic features of JSON serialization and conversions.

I currently have adapters for numpy (ndarray and dtype), scipy (Rotation), shapely (geometry types) and astropy (UnitBase, Quantity, PhysicalType and Time), along with some stuff from the standard library that pydantic doesn't ship with (slice, range, Ellipsis).

Target Audience

Users of both pydantic and common scientific libraries like: numpy, scipy, shapely and astropy.

Comparison

https://pypi.org/project/pydantic-numpy/

My project offers a few additional built-in features, such as more powerful shape specifiers, bounds checking and clipping. I don't support custom serialization, but this is just the first version of my project, that's on my list of future features.

https://pypi.org/project/pydantic-shapely/

This is pretty similar in scope. My project does WKT parsing in addition to GeoJSON and also offers coordinate bounds. Not a game-changer.

I don't know of anything else that offers scipy Rotation or astropy adapters.


r/Python • • Mar 03 '26

Daily Thread Tuesday Daily Thread: Advanced questions

5 Upvotes

Weekly Wednesday Thread: Advanced Questions 🐍

Dive deep into Python with our Advanced Questions thread! This space is reserved for questions about more advanced Python topics, frameworks, and best practices.

How it Works:

  1. Ask Away: Post your advanced Python questions here.
  2. Expert Insights: Get answers from experienced developers.
  3. Resource Pool: Share or discover tutorials, articles, and tips.

Guidelines:

  • This thread is for advanced questions only. Beginner questions are welcome in our Daily Beginner Thread every Thursday.
  • Questions that are not advanced may be removed and redirected to the appropriate thread.

Recommended Resources:

Example Questions:

  1. How can you implement a custom memory allocator in Python?
  2. What are the best practices for optimizing Cython code for heavy numerical computations?
  3. How do you set up a multi-threaded architecture using Python's Global Interpreter Lock (GIL)?
  4. Can you explain the intricacies of metaclasses and how they influence object-oriented design in Python?
  5. How would you go about implementing a distributed task queue using Celery and RabbitMQ?
  6. What are some advanced use-cases for Python's decorators?
  7. How can you achieve real-time data streaming in Python with WebSockets?
  8. What are the performance implications of using native Python data structures vs NumPy arrays for large-scale data?
  9. Best practices for securing a Flask (or similar) REST API with OAuth 2.0?
  10. What are the best practices for using Python in a microservices architecture? (..and more generally, should I even use microservices?)

Let's deepen our Python knowledge together. Happy coding! 🌟


r/Python • • Mar 02 '26

Discussion Chasing a CI-only Python Heisenbug: timezone + cache key + test order (and what finally fixed it)

0 Upvotes

Alright, story time. GitHub Actions humbled me so hard I almost started believing in ghosts again.

Disclosure: I contribute to AgentChatBus.

TL;DR

Locally: pytest ✅ forever.

CI: Random red (1 out of 5–10 runs), and re-running sometimes “fixes” it.

The "Heisenbug": Adding logging made the failure disapear.

Root cause: Global state leakage (timezone/config) + cache keys depending on implicit timezone context.

What helped: I ran a small AI agent debate locally via an MCP tool to break my own tunnel vision.

The symptoms (aka: the haunting)

This was the exact flavor of pain:

Run the failing test alone → Passes.

Run the full suite → Sometimes fails.

Re-run the same CI job → Might pass, might fail.

Add debug logs/prints → Suddenly passes. (Like it’s shy).

The error was in the “timezone-aware vs naive datetime” family, plus some cache weirdness where the app behaved like it was reading a different value than it just wrote. The stack trace, of course, tried to frame some innocent helper function. You know the vibe: the trace points to the messenger, not the murderer.

Why it only failed in CI

CI wasn’t magically broken — it was just:

Running tests in a different order.

Sometimes more paralelish.

In an environment where TZ/locale defaults weren’t identical to my laptop.

Any hidden order dependence finally had a chance to show itself.

The actual root cause (the facepalm)

It ended up being a 2-part crime:

The Leak: A fixture (or setup path) temporarily tweaked a global timezone/config setting but wasn't reliably restored in teardown.

The Pollution: Later tests then generated timestamps under one implicit context, built cache keys under another, or compared aware vs naive datetimes depending on which test polluted the process first.

Depending on the test order, you’d get cache key mismatches or stale reads because the “same” logical object got a different key. And yes: logging changed timing/execution enough to dodge the bad interleavings. I hate it here.

What fixed it (boring but real)

Normalize at boundaries: Make the “what timezone is this?” decision explicit (usually UTC/aware) whenever it crosses DB/cache/API boundaries.

Stop the leaks: Find fixtures that touch global settings (TZ, locale, env vars) and force-restore previous state in teardown no matter what.

Deterministic cache keys: Don’t let cache keys depend on implicit TZ. If time must be part of the key, normalize and serialize it consistently.

Hunt the flake: Add a regression test that randomizes order and runs suspicious subsets multiple times in CI.

CI has been boring green since. No sage burning required.

The “AI agent debate” part

At that point, I was basically one step away from trying an exorcism on my laptop. As a total Hail Mary, I remembered seeing something about ‘AI multi-agent debate’ for debugging. (I’d completely forgotten the name, so I actually had to go back and re-search it just for this write-up—it’s SWE-Debate, arXiv:2507.23348, for anyone keeping score).

Turns out, putting the AI into “full-on troll mode” is an absolute God-tier move for hunting Heisenbugs. I wasn't even looking for a direct solution from them; I just wanted to watch them ruthlessly tear apart each other’s hypotheses.

I ran a tiny local setup via an MCP tool where multiple agents took different positions:

“This is purely a tz-aware vs naive usage mismatch.”

“No, this is about cache key determinism.”

“You’re both wrong, this is fixture/global-state pollution.”

While the agents were busy bickering over which one of them was “polluting the environment,” it finally clicked: if logging changed the execution timing, something global was definitely leaking. The useful takeaway wasn’t “AI magic fixes bugs”—it was forcing competing explanations to argue until one explanation covered all the weird symptoms (CI-only, order dependence, logging changes).

That’s what pushed me to look for global config leakage instead of just staring at the stack trace.


r/Python • • Mar 02 '26

Showcase LANscape - A python based local network scanner

18 Upvotes

I wanted to show off one of my personal projects that I have been working on for the past few years now, it's called LANscape & it's a full featured local network scanner with a react UI bundled within the python library.

https://github.com/mdennis281/LANscape

What it does:

It uses a combination of ARP / TCP / ICMP to determine if a host exists & also executes a series of tests on ports to determine what service is running on them. This process can either be done within LANscape's module-based UI. or can be done importing the library in python.

Target audience:

It's built for anyone who wants to gain insights into what devices are running on their network.

Comparison :

The initial creation of this project stemmed from my annoyance with a different software, "Advanced IP Scanner" for it's general slowness and lack of configurable scanning parameters. I built this new tool to provide deeper insights into what is actually going on in your network.

It's some of my best work in terms of code quality & I'm pretty proud of what's its grown into.
It's pip installable by anyone who wants to try it & works completely offline.

pip install lanscape
python -m lanscape

r/Python • • Mar 02 '26

Discussion I built a DRF-inspired framework for FastAPI and published it to PyPI — would love feedback

15 Upvotes

Hey everyone,

I just published my first open source library to PyPI and wanted to share it here for feedback.

How it started: I moved from Django to FastAPI a while back. FastAPI is genuinely great — fast, async-native, clean. But within the first week I was already missing Django REST Framework. Not Django itself, just DRF.

The serializers. The viewsets. The routers. The way everything just had a place. With FastAPI I kept rewriting the same structural boilerplate over and over and it never felt as clean.

I looked around for something that gave me that DRF feel on FastAPI. Nothing quite hit it. So I built it myself.

What FastREST is: DRF-style patterns running on FastAPI + SQLAlchemy async + Pydantic v2. Same mental model, modern async stack.

If you've used DRF, this should feel like home:

python

class AuthorSerializer(ModelSerializer):
    class Meta:
        model = Author
        fields = ["id", "name", "bio"]

class AuthorViewSet(ModelViewSet):
    queryset = Author
    serializer_class = AuthorSerializer

router = DefaultRouter()
router.register("authors", AuthorViewSet, basename="author")

Full CRUD + auto-generated OpenAPI docs. No boilerplate.

You get ModelSerializer, ModelViewSet, DefaultRouter, permission_classes, u/action decorator — basically the DRF API you already know, just async under the hood.

Where it stands: Alpha (v0.1.0). The core is stable and I've been using it in my own projects. Pagination, filtering, and auth backends are coming — but serializers, viewsets, routers, permissions, and the async test client are all working today.

What I'm looking for:

  • Feedback from anyone who's made the same Django → FastAPI switch
  • Bug reports or edge cases I haven't thought of
  • Honest takes on the API design — what feels off, what's missing

Even a "you should look at X, it already does this" is genuinely useful at this stage.

pip install fastrest

GitHub: https://github.com/hoaxnerd/fastrest

Thanks 🙏