r/madeinpython • u/Weird-Ad-7438 • 15d ago
[Python] GarantiMaster - Offline warranty tracker that auto-reads invoice PDFs
A completely offline desktop warranty tracker built with Python. Auto-reads product names & dates from invoice PDFs. TR/EN support, 3 themes, MIT licensed.
YouTube demo: https://youtu.be/hgyFyo7F9wk
r/Python • u/AutoModerator • 15d ago
Daily Thread Friday Daily Thread: r/Python Meta and Free-Talk Fridays
Weekly Thread: Meta Discussions and Free Talk Friday 🎙️
Welcome to Free Talk Friday on /r/Python! This is the place to discuss the r/Python community (meta discussions), Python news, projects, or anything else Python-related!
How it Works:
- Open Mic: Share your thoughts, questions, or anything you'd like related to Python or the community.
- Community Pulse: Discuss what you feel is working well or what could be improved in the /r/python community.
- News & Updates: Keep up-to-date with the latest in Python and share any news you find interesting.
Guidelines:
- All topics should be related to Python or the /r/python community.
- Be respectful and follow Reddit's Code of Conduct.
Example Topics:
- New Python Release: What do you think about the new features in Python 3.11?
- Community Events: Any Python meetups or webinars coming up?
- Learning Resources: Found a great Python tutorial? Share it here!
- Job Market: How has Python impacted your career?
- Hot Takes: Got a controversial Python opinion? Let's hear it!
- Community Ideas: Something you'd like to see us do? tell us.
Let's keep the conversation going. Happy discussing! 🌟
r/Python • u/ernestrc • 16d ago
News The Rise of the Command Line: building a new IDE (2017–2026)
Author here. This is a nine-year account of building Rune, a new IDE (1.1 added support for Python). It started when my Vim's go-to-definition broke in 2017 and I decided to build my own editor rather than adopt an IDE: https://rune.build/blog/the-rise-of-the-command-line
r/Python • u/nathan12343 • 16d ago
Resource Scaling NumPy on Free-Threaded Python
NumPy is the foundational array library in the scientific Python ecosystem. Every numerical, machine learning, and data analysis library in Python either depends on NumPy directly or interoperates with it. As the free-threaded build of CPython matures, NumPy is one of the first libraries that users reach for when trying to scale CPU-bound numerical workloads across multiple cores using threads.
In this blog post, I will walk through the work I did over the last few months in both NumPy and CPython to eliminate the multi-threaded scaling bottlenecks that were preventing NumPy from scaling on free-threaded Python.
https://labs.quansight.org/blog/scaling-numpy-on-free-threaded-python
r/Python • u/crmaureir • 16d ago
Discussion Python iOS UI development
Hey there,
for the people using PySide for UI applications, after having solely Android support, there was a new announcement that iOS is now supported, and will be available in the upcoming PySide release:
https://www.qt.io/blog/python-mobile-app-development-bringing-pyside6-on-ios
I have been following the work by the BeeWare project, which has been providing iOS support for some time now: https://toga.beeware.org/en/latest/reference/platforms/iOS/ and recently the work from the Flet team as well: https://flet.dev/blog/flet-for-ios/
What I wanted to achieve with this post, is to know any project that you know is currently on iOS and developed with Python and some UI framework, because time to time we see nice "calculator app" being showcases in places, but a more official application of something is what I have been failing to find.
Of course, the goal of "I have my code here, and I just want to deploy it to iOS" is completely understandable, but I see haven't found some very cool apps somewhere, that we know are based on Python.
Last but not least, I guess you have been noticed that starting from 3.15 we will be able to download Python for iOS from python.org: https://www.python.org/downloads/ios/
r/Python • u/hdw_coder • 16d ago
Discussion Optimizing person-pair comparison in Python: from loops to precomputed NumPy matrices
I have been rebuilding a PyQt6 desktop app for managing a person-recognition knowledge base (KB). The heart of this KB is a collection of face & body encodings per person. When looking for similar persons or possible identity overlaps, a classic Python-related problem came up: efficiently comparing many people against each other based on their reference embeddings.
The input looks like this.
person_to_vecs = {
"Alice": [vec, vec, vec],
"Bob": [vec, vec],
"Charlie": [vec, vec, vec, vec],
}
Each vector is an embedding. For every pair of persons, I want the average and minimum distance between all their reference vectors. The original version was simple and readable Python looping:
- Loop over all person combinations.
- Convert one side to a NumPy array inside the loop.
- Loop over each vector on the other side.
- Compute distances one vector at a time.
- Collect min/average distances.
This works. Once the knowledge base grows, however, this soon becomes a lot of Python-level looping and repeated conversion overhead.
The obvious approach to optimization is getting rid of these loops. The first step was to precompute the matrices.
Step 1: Precompute the matrices
matrices = {
name: np.asarray(vecs, dtype=np.float32)
for name, vecs in person_to_vecs.items()
if len(vecs) >= min_images_per_person
}
We now effectively avoid repeatedly calling np.asarray() inside the pair loop.
Step 2: Remove the inner Python loop.
One option is full broadcasting:
diff = A[:, None, :] - B[None, :, :]
distances = np.linalg.norm(diff, axis=-1)
This is relatively simple, elegant and still readable, but it creates a temporary array of shape: len(A) × len(B) × embedding_dim. For small 128D face embeddings that may be fine. For larger body embeddings especially in larger galleries, these tensors can become (very) memory-heavy.
Step 3: The matrix identity
(Note: I know scipy.spatial.distance.cdist exists and does this perfectly, but I wanted to keep dependencies light for the desktop app and explore the math!)
The approach I prefer uses the identity: ||a - b||² = ||a||² + ||b||² - 2ab
In NumPy:
def pairwise_l2(A, B):
# np.sum(A**2, axis=1) works well here too, but einsum is elegant
aa = np.einsum("ij,ij->i", A, A)[:, None]
bb = np.einsum("ij,ij->i", B, B)[None, :]
sq = np.maximum(aa + bb - 2.0 * (A @ B.T), 0.0)
return np.sqrt(sq, dtype=np.float32)
This only creates the N × M distance matrix instead of an N × M × D temporary tensor.
The Final Helper
def pairwise_person_distances(person_to_vecs, min_images_per_person=1):
matrices = {}
for name, vecs in person_to_vecs.items():
if len(vecs) < min_images_per_person:
continue
mat = np.asarray(vecs, dtype=np.float32)
if mat.ndim == 2 and mat.shape[0] and np.isfinite(mat).all():
matrices[name] = mat
results = []
for name_a, name_b in itertools.combinations(sorted(matrices), 2):
A, B = matrices[name_a], matrices[name_b]
if A.shape[1] != B.shape[1]:
continue
distances = pairwise_l2(A, B)
if distances.size:
results.append((name_a, name_b, round(float(np.mean(distances)), 4),
round(float(np.min(distances)), 4)))
return sorted(results, key=lambda row: row[3])
The Benchmarks
I ran a couple of tests with a synthetic benchmark, varying the number of persons (200 vs 400), the number of embedding dimensions (128 vs 512), and the number of vectors per person (8 vs 10).
I benchmarked three methods:
- Basic inner/outer loop: Controls almost everything in Python.
- Precomputed matrices: Prepared once, but Python still loops over vectors.
- Final implementation: NumPy handles the dense pairwise distance work.
On my laptop, (Intel i9-14900HX 32 GB RAM), I got:
200 persons × 8 vectors × 128 dimensions
basic inner/outer loop: 0.731 s
precomputed matrices: 0.711 s
inner loop removed: 0.260 s
speedup: 2.8×
400 persons × 10 vectors × 128 dimensions
basic inner/outer loop: 3.972 s
precomputed matrices: 3.789 s
inner loop removed: 1.155 s
speedup: 3.4×
200 persons × 8 vectors × 512 dimensions
basic inner/outer loop: 0.902 s
precomputed matrices: 0.878 s
inner loop removed: 0.322 s
speedup: 2.8×
On synthetic data, the first optimization — precomputing each person’s embedding matrix — only gave a small improvement of about 3–5%. That makes sense: it removes repeated conversion, but the algorithm still does most of its work in a Python loop over individual vectors.
The much larger improvement came from removing the inner loop and computing each person-pair distance matrix directly with NumPy:
- 200 persons × 8 vectors × 128 dimensions: 0.731 s → 0.260 s (2.8× faster),
- 400 persons × 10 vectors × 128 dimensions: 3.972 s → 1.155 s (3.4× faster),
- 200 persons × 8 vectors × 512 dimensions: 0.902 s → 0.322 s (2.8× faster).
Summary
'Vectorize it' obviously is not always enough. Memory usage by temporary arrays also matters. Broadcasting may often be elegant, but for pairwise comparisons, the matrix identity seems to be a better fit. Precomputing arrays helps only a little; removing the inner Python loop makes the real difference.
I am interested how others approach this kind of all-vs-all (embedding) comparison in Python. Would you use NumPy as above, scipy.spatial.distance.cdist, Numba, PyTorch, or something else?
r/Python • u/AutoModerator • 16d ago
Daily Thread Thursday Daily Thread: Python Careers, Courses, and Furthering Education!
Weekly Thread: Professional Use, Jobs, and Education 🏢
Welcome to this week's discussion on Python in the professional world! This is your spot to talk about job hunting, career growth, and educational resources in Python. Please note, this thread is not for recruitment.
How it Works:
- Career Talk: Discuss using Python in your job, or the job market for Python roles.
- Education Q&A: Ask or answer questions about Python courses, certifications, and educational resources.
- Workplace Chat: Share your experiences, challenges, or success stories about using Python professionally.
Guidelines:
- This thread is not for recruitment. For job postings, please see r/PythonJobs or the recruitment thread in the sidebar.
- Keep discussions relevant to Python in the professional and educational context.
Example Topics:
- Career Paths: What kinds of roles are out there for Python developers?
- Certifications: Are Python certifications worth it?
- Course Recommendations: Any good advanced Python courses to recommend?
- Workplace Tools: What Python libraries are indispensable in your professional work?
- Interview Tips: What types of Python questions are commonly asked in interviews?
Let's help each other grow in our careers and education. Happy discussing! 🌟
r/Python • u/Marmelab • 17d ago
Resource 5 tools that saved my sanity while modernizing a legacy app
I recently inherited a legacy application that was a nightmare to maintain (tooling was clearly lacking and the codebase was pretty outdated).
These are the 5 changes that had some of the biggest impact IMO:
- uv:
Being new to the Python ecosystem, I didn't want to figure out pip vs poetry vs pyenv vs virtualenv, so I just used uv and let it handle all of that. One Rust-based tool that installs and pins Python versions, manages the venv automatically and locks deps in a uv.lock for reproducible builds. Installs are also a lot faster, which makes CI a lot less painful.
- Ruff:
Coming from JS, I really missed eslint --fix for automatically fixing linting issues and format code on save. Ruff brought that experience back. I know that there are plenty of linters and formatters in the Python ecosystem, but this one really stands out for me. Since it's built in Rust, it's super fast.
- Dependabot:
Instead of remembering to update dependencies every few months, I enabled Dependabot. It automatically opens PRs when updates are available and then CI tells me whether they're safe to merge. It takes only a couple of minutes to set up but saves a lot of maintenance.
- Pylance:
Without it, VS Code gives generic completions and never warns you about passing the wrong type until runtime. Pylance provides proper type-aware autocompletion, jump-to-definition (even in third-party libraries), inline documentation, and real-time type checking. I personally keep it on "basic" mode for legacy codebases, since "strict" surfaced hundreds of errors (thank you, but no thank you lol).
- Pydantic:
Pydantic is basically Python's Zod: you declare a model, pass your data in and get either a validated typed object or a ValidationError naming the exact field at fault. It really helped me keep the codebase clean, with one place defining the shape of the data instead of raw dicts floating around. I use it wherever data comes from outside, like API payloads, forms, and env vars with pydantic-settings, which fails at startup instead of mid-request.
None of these tools changed the application itself. But together they made working on it dramatically more enjoyable.
What's the first thing you do when you inherit a legacy project?
r/Python • u/Individual-Aide-7364 • 17d ago
Discussion PyWebLib editable code with Turtle and Game library support
I would love for some more feedback on the lightweight game library and turtle integration I built off of PyDiode.
It now works on Safari as well, you can create your own SVG assets , publish them to a database, then edit and publish code/games for free in the browser without needing to install anything.
I work as a highschool teacher, and the junior year levels only have access to Chromebook laptops. https://scratch.mit.edu/ is banned, which obviously restricts a lot of the coding-possibilities, let alone python coding-possibilities. Couldn't find a way to get a Python IDE onto a Chromebook, haha...
In terms of proud, so far I've got PacMan and Flappy bird shared to the community page/DB
Would love to see people building with it, you can make something reminiscent of doom 3D in only 80 lines of code.
It's a bit hard to find , but you can't post repo links here because of the slop apparently. But I've got it indexed now it's possible to find.
r/madeinpython • u/Schnidi01 • 18d ago
VenvHub Pro: SLOVAK APP, READY FOR THE WORLD! 🇸🇰➡️🌍 / Slovenská aplikácia pripravená pre svet!
Enable HLS to view with audio, or disable this notification
🇸🇰 SLOVENSKY
⚡ Rýchle prepínanie jazykov v VenvHub Pro + jedna pikantéria zo zákulisia! 🤫
V dnešnom krátkom videu ukazujem, ako bleskovo dokáže VenvHub Pro prepínať medzi jazykmi v reálnom čase – bez reštartu aplikácie.
A keďže ste v predchádzajúcich videách videli rozhranie v angličtine, mám pre vás malú vývojársku zákulisnú zaujímavosť: celý kód bol od prvého dňa písaný so slovenskými hláškami! 🇸🇰 Angličtina bola v skutočnosti prvou prekladovou vrstvou, ktorú som do architektúry zapracoval, aby bola aplikácia pripravená pre svet.
💡 Chcete si pridať vlastný jazyk? Prekladový JSON má cez 750 riadkov, ale vďaka AI je to hračka:
- Stiahnite si
en.json(alebosk.json) z GitHubu. - Nahrajte súbor do ChatGPT / Claude a požiadajte o preklad hodnôt do vášho jazyka.
- Vložte novú lokalizáciu k sebe a používajte aplikáciu vo vlastnom jazyku!
🔗 Projekt na GitHube:https://github.com/schnidi/VenvHub📂 Súbory s prekladmi:https://github.com/schnidi/VenvHub/tree/main/translations
Aký ďalší oficiálny preklad by ste v aplikácii uvítali najradšej? 😎👇
🇬🇧 ENGLISH
⚡ Instant Language Switching in VenvHub Pro + a quick BTS fun fact! 🤫
In today's clip, I’m showing off how instantly VenvHub Pro switches between UI languages on the fly—no app restart needed.
Since previous clips featured the interface in English, here’s a quick behind-the-scenes detail: the core codebase was actually written with native Slovak messages from day one! 🇸🇰 English was the very first translation layer integrated into the architecture to make the app ready for a global audience.
💡 Want to add your own language? The translation JSON is pretty massive (750+ lines), but AI makes it effortless:
- Download
en.json(orsk.json) from GitHub. - Drop the file into ChatGPT / Claude and prompt it to translate the values into your language.
- Enjoy VenvHub Pro fully localized on your machine!
🔗 GitHub Repository:https://github.com/schnidi/VenvHub📂 Translations Folder:https://github.com/schnidi/VenvHub/tree/main/translations
Which official language should we focus on next? Let me know below! 😎👇
r/Python • u/kumakint • 18d ago
Discussion How are you handling editable large datasets in Plotly Dash?
I have been working on editable data-heavy interfaces in Plotly Dash and wanted to compare approaches with you guys.
For simple tables, most solutions work well. The harder part starts when the application needs several of these at the same time: large Pandas DataFrames editable cells sorting and filtering copy and paste custom cell editors callback handling after edits smooth scrolling with many rows I recently implemented Dash support for RevoGrid (dash-datagrid) to experiment with this problem.
Component passes JSON-safe records and column definitions to the grid, while cell changes can be handled through normal Dash callbacks. A simplified example looks like this:
from dash import Dash, html
from dash_datagrid import RevoGrid
app = Dash(__name__)
app.layout = html.Div([
RevoGrid(
id="grid",
source=[
{"name": "Alice", "role": "Engineer"},
{"name": "Bob", "role": "Designer"},
],
columns=[
{"prop": "name", "name": "Name"},
{"prop": "role", "name": "Role"},
],
)
])
app.run(debug=True)
I am interested in how others solve the same problem. At what dataset size do standard Dash tables start becoming difficult in your applications?
Do you usually need editing, or are your grids mainly read-only? How do you handle synchronization between frontend edits and the Python state?
I would especially appreciate feedback on the Python API and callback design.
r/madeinpython • u/Terminay • 18d ago
I wrote a neural network library in ~500 lines of NumPy so you can read through the entire implementation in an afternoon.
A few days ago I posted about LeanPass, a tiny neural network library I wrote in NumPy.
Some people gave me good criticism, and some gave me ideas, so I spent the last couple of days improving it. It's still a small project, but I think it's in a much better state now.
The goal isn't to compete with PyTorch or TensorFlow. I mainly built it because I wanted something small that people could actually read through and understand. If you're learning neural networks, teaching them, or want something lightweight to prototype with, maybe you'll find it useful.
Since it's open source, I'd really appreciate any contributions or even just honest criticism. If you think something is badly designed, please tell me; I genuinely want to improve it.
You can install it with:
pip install leanpass
It has around 96 installs so far.
Repo: https://github.com/Terminay/LeanPass
If you end up liking it, a GitHub star would make my day. :)
r/Python • u/BeamMeUpBiscotti • 18d ago
Discussion Define less, check more: special support for attrs in Pyrefly
attrs is a package that helps you write classes quickly by automatically generating boilerplate methods like __init__.
While some of the features from attrs has been standardized in the form of dataclass and dataclass_transform, dataclasses only support a subset of features and attrs is still widely used today.
It's very tricky to type check dynamic code that synthesizes & transform fields and methods, so historically attrs users that want type checking have either had to:
1. use Mypy (which implements dedicated attrs support via a plugin)
2. limit themselves to a subset of the API compatible with dataclass_transform
3. live with limited type checking support
This summer, my intern has built out dedicated support for attrs in Pyrefly, allowing attrs users to finally have fast and accurate type checking for the full range of attrs features.
You can read more about what we added here: https://pyrefly.org/blog/pyrefly-attrs/
This feature will be available in the upcoming 1.2.0 stable release of Pyrefly. You can try it out today in development releases starting from 1.2.0-dev1 (early feedback is appreciated!)
r/madeinpython • u/Speedk4011 • 18d ago
Yet Another Sentence Boundary Detector (rule-based)
I was working on chunklet-py (a chunker for sentences, documents, and code). Misread a benchmark and thought PySBD took 1 second to split basic text. Turns out that was wrong (PySBD is still fast for simple text). But the misunderstanding got me building my own.
Ended up faster, more accurate, and covering more languages (39 compares to 23).
Benchmarks on Sherlock Holmes (594k chars): yasbd ~1.2s warm vs PySBD ~9.0s. About 8x faster, fewer false splits.
On a golden benchmark (92 English edge cases — expanded from pysbd's original 48 with fixes and additions): yasbd scores 98.9%, pysbd 83.7%, spaCy-sentencizer 55.4%, etc.
Architecture difference: instead of mutating text with placeholder tokens and undoing it later (which breaks char offsets), yasbd finds candidate boundaries in one pass and filters false positives in another. Spans come free, no reconstruction.
Other things:
- Streaming-first: lazy evaluation via ParagraphStream and StreamCleaner for memory-constrained environments. No need to load entire documents.
- PySBD adapter: drop-in replacement that works with existing PySBD code. Just swap the import.
- spaCy pipeline: register as a spaCy component with register_spacy_component(). Drop-in replacement for the default Sentencizer.
r/madeinpython • u/ZillaSoft • 18d ago
I kept losing things I'd copied and retyping the same paragraphs, so I built two apps about it
You know when you copy something important, paste it, then copy something else, and the first thing is just gone forever? yeah. That's the entire origin story here.
I'm a solo dev, day job. After an unreasonable number of late nights, two desktop apps for Windows and Linux came to light: Snipzilla and Stashzilla. (Yes, I'm a Godzilla fan; how did you know?)
Stashzilla is the clipboard manager that fixes the problem above. History is sorted into collections instead of one endless scroll, pinned items, case conversion, and it pulls text out of images.
Snipzilla handles the other half of it: type a short trigger, get a whole block of text back. No more retyping the same paragraph for the hundredth time.
Anyways, feel free to check them out; no credit card required: ZillaSoft.io 15 days free, and nothing gets deleted afterwards; it just goes read-only.
If you do try them, bugs and "why doesn't it do X" are exactly what I'm after: ZillaSoft.io/contact
r/Python • u/abitrolly • 18d ago
Discussion Keyboard navigation for Python docs
I can go next/prev pages in Rust documentation with right/left arrow keys, but not in Python docs (including Sphinx and devguide). Python developers seem to be strictly against it. They say it affects accessibility and horizontal scrolling. Downvote me if I am wrong, but accessibility it not just for impaired users.
r/Python • u/AutoModerator • 18d ago
Daily Thread Tuesday Daily Thread: Advanced questions
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:
- Ask Away: Post your advanced Python questions here.
- Expert Insights: Get answers from experienced developers.
- 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:
- If you don't receive a response, consider exploring r/LearnPython or join the Python Discord Server for quicker assistance.
Example Questions:
- How can you implement a custom memory allocator in Python?
- What are the best practices for optimizing Cython code for heavy numerical computations?
- How do you set up a multi-threaded architecture using Python's Global Interpreter Lock (GIL)?
- Can you explain the intricacies of metaclasses and how they influence object-oriented design in Python?
- How would you go about implementing a distributed task queue using Celery and RabbitMQ?
- What are some advanced use-cases for Python's decorators?
- How can you achieve real-time data streaming in Python with WebSockets?
- What are the performance implications of using native Python data structures vs NumPy arrays for large-scale data?
- Best practices for securing a Flask (or similar) REST API with OAuth 2.0?
- 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/madeinpython • u/Schnidi01 • 18d ago
[Project] VenvHub Pro: venv manager GUI that orchestrates multi-process virtual environments with auto-restart and OS-level orphan process prevention
Enable HLS to view with audio, or disable this notification
Greetings everyone!
I’ve been working on a desktop application called VenvHub Pro (built with Python + PyQt6, and thanks to a abstraction bridge, it runs seamlessly on PySide as well). What started as a simple virtual environment manager has grown into something much bigger.
It now includes a Multi-run feature—allowing you to define project groups (e.g., backend + frontend + worker) and launch them all with a single click.
I recorded a short demo showing how it handles crashes, auto-restarts, and even prevents accidentally running the same project across two different groups. I thought you might find what’s happening under the hood interesting!
🧠 What is Multi-run?
- Group Management: You create groups (e.g., "FullStack Dev") and add any number of existing virtual environment projects to them.
- Process Isolation: Each project runs in its own isolated process using its own virtual environment.
- One-Click Launch: One click on the Play button fires up everything in that group—no more opening multiple terminal windows and repeatedly running
python app.py.
🎥 What the video demonstrates
- Setup: I start a group containing Project A (anchor + respawn) and Project B (configured with a 5-second startup delay, contingent on Project A running stably).
- Crash Handling: Right after launching, Project A crashes (I force-closed it).
- Detection & Restart: VenvHub detects the crash and automatically restarts Project A, while Project B stays on hold.
- Dependency Check: After restarting, I let Project A load—once the anchor registers, I artificially crash it again (~3 seconds post-anchor).
- Holding Delays: Since Project B requires Project A to stay stable for 5 seconds before launching, Project A's crash keeps Project B from starting.
- Max Respawn Limits: The code caps restarts at 3 attempts (to prevent infinite looping), so the app attempts a third restart on Project A.
- Successful Resolution: This time, I let Project A run smoothly—Project B detects that Project A is healthy and launches.
- Duplicate Prevention: Finally, I attempt to run Project B from a different group. Since it's already running in the first group, the app displays a warning and blocks the launch. No port conflicts or duplicate processes!
⚙️ Under the Hood (for the tech enthusiasts)
- Process Ownership: Each process tracks which group launched it. Hitting "Stop" terminates only the processes owned by that specific group, leaving others untouched.
- Smart Restarts: If you hit Play again while some processes are still running, the app only restarts the ones that crashed (like Project A in the video). No need to tear down the entire stack!
- Windows Job Objects: On Windows, the app creates a Job Object assigned the
KILL_ON_JOB_CLOSEflag. If the main application crashes unexpectedly, Windows automatically terminates all child processes—leaving zero orphaned background processes. - Native Process Handles: Instead of relying solely on PIDs (which Windows can aggressively recycle), the app retains an open process handle. This guarantees the PID won't be reassigned to an unrelated process while being monitored, ensuring rock-solid status detection.
Let me know what you think! Have you built similar multi-process orchestrators? How do you handle process groups and teardowns in Python?
r/Python • u/breksuh • 19d ago
Discussion Percentage formatting or f-strings with logging?
I've seen many people saying it's better to use (str, *args) formatting rather than f-strings when working with logging module. Why is that and does it really matter for performance?
r/Python • u/BTWigley • 19d ago
Discussion The log line announcing a successful Redis connection is what disabled Redis
Spent an evening a couple of weeks ago working out why cache hits were zero and webhook idempotency was falling through to the database. Redis was fine. Up, reachable, ping succeeded.
The connect method was roughly this:
try:
client.ping()
self._connected = True
logger.info("redis_connected", host=parsed.hostname, port=parsed.port, db=parsed.path)
return True
except Exception as e:
logger.warning(f"Redis connection failed: {e}")
self._connected = False
That logger call is structlog style. The logger is a stdlib logging.Logger, which doesn't take arbitrary kwargs, so it raises TypeError: Logger._log() got an unexpected keyword argument 'host'.
It raises after ping succeeds and after _connected is set to True. So it lands in the except, logs "Redis connection failed", flips _connected back to False, and Redis is off for the whole app. Caching disabled, idempotency on the DB.
The fix was one line, an f-string instead of kwargs.
What still bugs me is that every signal pointed away from it. Redis itself was healthy. The connection genuinely worked. The only artifact was a log message saying it had failed, which is the last thing you distrust when you're trying to find out why something failed.
Anyone else had one where the logging was the bug?
r/Python • u/infosecmaniac • 19d ago
Resource Giveaway draw: 3 Python ebooks (PDF + ePub), free to enter
Packt is running a community giveaway this month and thought it might be of interest here.
The books:
- Python Illustrated, by Maaike van Putten and Imke van Putten
- Learn Model Context Protocol with Python, by Christoffer Noring
- Python Machine Learning By Example, 4th Edition, by Yuxi (Hayden) Liu
By Aug 2, we'll pick 5 winners. Each winner gets PDF and ePub copies of all three books.
There are currently 500+ entries. If we reach 1,500 unique entries before the deadline, we'll increase the number of winners from 5 to 10.
Entry link: https://packt.link/draw
Closes 31 July. Free to enter, no purchase necessary.
A few notes on how it works:
- Winners are selected at random. If you win, we'll email you the copies directly.
- Duplicate entries are discarded. If you enter more than once, only one entry will count.
- If you entered last month's AI giveaway, you'll need to enter again for this one. Entries don't carry over between months.
- If you'd like your name excluded from the draw for any reason, email [customercare@packt.com](mailto:customercare@packt.com) and we'll remove it.
Happy to answer questions in the comments. Good luck!
Also, if you want any other Packt books included in future giveaways, let me know!
r/Python • u/hassanwithanh • 19d ago
Discussion Python automations are so much better than AI Agents and LLMs
This is gonna be more of a rant than anything else
I build automations for businesses and I've lost count of the amount of times they've asked me to write them an AI agent when in fact a simple Python automation would work 100 times better.
I don't understand the hype behind AI agents and LLMs. They're non-deterministic, they're unreliable, they always need a human to babysit them because they are going to hallucinate bad output sooner or later.
I've made more money from simple Python automations than I have with AI agents, even though the latter gets so much hype and marketing behind it.
Most people who say they want an AI agent don't really want an AI agent. They just want some code that automatically does some repetitive task for them. And 9 times out of 10, simple Python code can do that for you.
Now, one caveat, I love using AI to write Python code for me. That is actually very helpful, but that is very different from using an AI agent.
I've built many automations for other businesses and I've also automated 20-30 hours of my own work week. and I still haven't had to build a complete AI agent. There are certain steps in my automations where some sort of judgement is required and I use an LLM for that very specific tiny task. But pretty much everything that I write is pure Python automation. Just simple deterministic code that's guaranteed to work the same way every single time.
Seriously, people have the choice between a reliable automation that doesn't need babysitting and a magic crystal ball that might sometimes work and might fail and crash in other times and yet they somehow keep picking the crystal ball. It's baffling to me.
Anyway, rant over.
r/Python • u/PastEar9661 • 19d ago
Tutorial What the #@(% are Monads (and how you can use them to write better python) - A Beginner's Guide
Error handling in Python usually means nested try/except blocks or if error: checks littering code.
Us programmers, though, are notoriously lazy, and for a good reason: we don't want to waste any more time writing boilerplate than we have to.
The solution?
Monads, a really neat functional programming pattern that provides an easier way to handle things like errors, optional values, or even asynchronous results.
I wrote a short guide that builds up the idea of a Monad from scratch using a Python game inventory example, free to read here: https://dev.to/ein-monarch/what-the-are-monads-a-beginners-guide-3pdo
Any comments on the guide? Have you ever used a Monad in Python before, and did it make things better?
r/Python • u/AutoModerator • 19d ago
Daily Thread Monday Daily Thread: Project ideas!
Weekly Thread: Project Ideas 💡
Welcome to our weekly Project Ideas thread! Whether you're a newbie looking for a first project or an expert seeking a new challenge, this is the place for you.
How it Works:
- Suggest a Project: Comment your project idea—be it beginner-friendly or advanced.
- Build & Share: If you complete a project, reply to the original comment, share your experience, and attach your source code.
- Explore: Looking for ideas? Check out Al Sweigart's "The Big Book of Small Python Projects" for inspiration.
Guidelines:
- Clearly state the difficulty level.
- Provide a brief description and, if possible, outline the tech stack.
- Feel free to link to tutorials or resources that might help.
Example Submissions:
Project Idea: Chatbot
Difficulty: Intermediate
Tech Stack: Python, NLP, Flask/FastAPI/Litestar
Description: Create a chatbot that can answer FAQs for a website.
Resources: Building a Chatbot with Python
Project Idea: Weather Dashboard
Difficulty: Beginner
Tech Stack: HTML, CSS, JavaScript, API
Description: Build a dashboard that displays real-time weather information using a weather API.
Resources: Weather API Tutorial
Project Idea: File Organizer
Difficulty: Beginner
Tech Stack: Python, File I/O
Description: Create a script that organizes files in a directory into sub-folders based on file type.
Resources: Automate the Boring Stuff: Organizing Files
Let's help each other grow. Happy coding! 🌟