r/Python • u/One-Type-2842 • Apr 02 '26
Discussion Is match ... case In Python Reliable as if .. elif .. else
What are your Views and Counterviews on match case condition checking In Python?
Are they Reliable as if elif else statement?
r/Python • u/One-Type-2842 • Apr 02 '26
What are your Views and Counterviews on match case condition checking In Python?
Are they Reliable as if elif else statement?
r/Python • u/Ousret • Apr 02 '26
When I started working on Niquests, I dreamed about a "no-compromise" HTTP client, and three years later I finally made it to the end.
The end goal was, at least for me, to reach what the world of today allows us to, today. And, unfortunately the Python community is often stuck with decade old capabilities. (ie. http/1 only, legacy ssl capabilities, ...).
Niquests started as a fork of Requests in mid-2023. The motivation was simple: Requests is frozen, and millions of developers are stuck with a library that does not evolve (feature-wise). I didn't want to reinvent the wheel, the Requests interface is genuinely pleasant to work with. I just wanted to bring it up to speed with what modern HTTP looks like.
What changed in three years?
A lot. Here's some key things:
response.conn_info.And it's fast, I mean really fast. In a real-world benchmark (details and reproduction steps in the README) sending 1000 requests to httpbingo.org/get:
| Client | Avg time to complete | Protocol |
|---|---|---|
| httpx | 2.087s | HTTP/2 |
| aiohttp | 1.351s | HTTP/1.1 |
| niquests | 0.551s | HTTP/2 |
Migration starts as a one-liner. Replace import requests with import niquests as requests and you're done. We maintain backward compatibility with the Requests API. Your existing code, your .netrc, your auth flows, your cookie jars -- they all work. Even requests-mock, responses, betamax and similar third-party extensions are supported with minimal shims.
It's getting some real traction lately. We're about to cross the 100k pulls per day from PyPI alone, Niquests appearing more commonly in Github code search engine, and folks creating issues whether they found a bug or just to challenge the solution. That's excellent news!
It's been more than a decade since I started doing open source, and so far, it's nowhere near boring me. I'll answer the community as long as I possibly can.
Niquests is a HTTP Client. It aims to continue and expand the well established Requests library. For many years now, Requests has been frozen. Being left in a vegetative state and not evolving, this blocked millions of developers from using more advanced features.
It is a production ready solution. So everyone is potentially concerned.
Niquests is the only HTTP client capable of serving HTTP/1.1, HTTP/2, and HTTP/3 automatically. The project went deep into the protocols (early responses, trailer headers, etc...) and all related networking essentials (like DNS-over-HTTPS, advanced performance metering, etc..)
Project page: https://github.com/jawah/niquests
r/Python • u/gidorah5 • Apr 02 '26
Hello redditors,
I've been playing around with a builder pattern in Python, and I was trying to achieve a builder pattern with correct typehinting, However, I can't seem to get some of my types working.
The goal is to create a pipeline, that can have a variable amout of steps. The pipeline have a TIn and TOut type that should be infered from the inner steps (TIn being the input of the first step, and TOut the output of the last step)
Here is my current implementation:
TIn = TypeVar("TIn")
TOut = TypeVar("TOut")
TNext = TypeVar("TNext")
class Step(ABC, Generic[TIn, TOut]):
def execute(self, data: TIn) -> TOut:
...
def create_process(step: Step[TIn, TOut]) -> "Process[TIn, TOut]":
return Process.start_static(step)
class Process(Generic[TIn, TOut]):
def __init__(self, steps: list[Step] | None = None):
self.steps: list[Step] = steps or []
@classmethod
def start_class(cls, step: Step[TIn, TOut]) -> "Process[TIn, TOut]":
return cls([step])
@staticmethod
def start_static(step: Step[TIn, TOut]) -> "Process[TIn, TOut]":
return Process([step])
def add_step(self, step: Step[TOut, TNext]) -> "Process[TIn, TNext]":
return Process(self.steps + [step])
def execute(self, data: TIn) -> TOut:
current = data
for step in self.steps:
print(type(step))
current = step.execute(current)
return cast(TOut, current)
class IntToStr(Step[int, str]):
def execute(self, data: int) -> str:
return str(data)
class StrToBool(Step[str, bool]):
def execute(self, data: str) -> bool:
return data != ""
process = create_process(IntToStr()).add_step(StrToBool())
# ^^ type Process[int, bool]
process = Process().add_step(IntToStr()).add_step(StrToBool())
# ^^ type Process[Unknown, bool]
process = Process.start_static(IntToStr()).add_step(StrToBool())
# ^^ type Process[Unknown, bool]
process = Process.start_class(IntToStr()).add_step(StrToBool())
# ^^ type Process[Unknown, bool]
process.execute(1)As you can see, the only way I've been able to correctly infer the input type is by using a method outside of my class.
I'm not sure what is causing this, and I was wondering if anyone knew a workaround this issue, or am I doomed to use a Factory method.
I would believe that the issue is caused because TIn is not defined for the first step, thus issuing an Unknown.
Have a great day y'all !
r/Python • u/MLPhDStudent • Apr 02 '26
Tl;dr: One of Stanford's hottest AI seminar courses. We open the course to the public. Lectures start tomorrow (Thursdays), 4:30-5:50pm PDT, at Skilling Auditorium and Zoom**. Talks will be** recorded. Course website: https://web.stanford.edu/class/cs25/.
Interested in Transformers, the deep learning model that has taken the world by storm? Want to have intimate discussions with researchers? If so, this course is for you!
Each week, we invite folks at the forefront of Transformers research to discuss the latest breakthroughs, from LLM architectures like GPT and Gemini to creative use cases in generating art (e.g. DALL-E and Sora), biology and neuroscience applications, robotics, and more!
CS25 has become one of Stanford's hottest AI courses. We invite the coolest speakers such as Andrej Karpathy, Geoffrey Hinton, Jim Fan, Ashish Vaswani, and folks from OpenAI, Anthropic, Google, NVIDIA, etc.
Our class has a global audience, and millions of total views on YouTube. Our class with Andrej Karpathy was the second most popular YouTube video uploaded by Stanford in 2023!
Livestreaming and auditing (in-person or Zoom) are available to all! And join our 6000+ member Discord server (link on website).
Thanks to Modal, AGI House, and MongoDB for sponsoring this iteration of the course.
r/Python • u/AutoModerator • Apr 02 '26
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.
Let's help each other grow in our careers and education. Happy discussing! 🌟
r/Python • u/mikeckennedy • Apr 01 '26
Over the past few weeks I went on a memory-reduction tear across the Talk Python web apps. We run 23 containers on one big server (the "one big server" pattern) and memory was creeping up to 65% on a 16GB box.
Turned out there were a bunch of wins hiding in plain sight. Focusing on just two apps, I went from ~2 GB down to 472 MB. Here's what moved the needle:
Total across all our apps: 3.2 GB freed. Full write-up with before/after tables and graphs here: https://mkennedy.codes/posts/cutting-python-web-app-memory-over-31-percent/
r/Python • u/Intelligent-Role-382 • Apr 01 '26
Hi everyone, I have around 5 years of experience in IT and I’m planning to build complex, industry-level desktop applications using Python. I’m evaluating different options and feeling a bit confused about what’s actually used in real-world projects. The main options I’m considering are: PySide (Qt for Python) PyQt wxPython Kivy Python backend + web frontend (React/Angular) wrapped in Electron My goal is strictly desktop applications (not SaaS/web apps), and I’m trying to choose something that is: Used in the industry Scalable for large applications Good for long-term maintainability and career growth From what I’ve researched: Qt-based (PySide/PyQt) seems most powerful wxPython looks more native but less modern Kivy seems more for touch/mobile-style apps Web-based approach looks modern but heavier I’d really like input from people with real industry experience: 👉 Which of these is actually used in companies for serious desktop applications? 👉 Is PySide preferred over PyQt nowadays? 👉 Is wxPython or Kivy used in production anywhere significant? 👉 When does it make sense to choose a web-based desktop app instead? Would really appreciate honest opinions and real-world insights. Thanks!
r/Python • u/BeamMeUpBiscotti • Apr 01 '26
On the Pyrefly team, we've always believed that type coverage is one of the most important indicators of code quality. Over the past year, we've worked closely with teams across large Python codebases at Meta - improving performance, tightening soundness, and making type checking a seamless part of everyday development.
But one question kept coming up: What would it take to reach 100% type coverage?
Today, we're excited to share a breakthrough ;-)
Link to full blog: https://pyrefly.org/blog/100-percent-type-coverage/
r/Python • u/A-Busi6711 • Apr 01 '26
I’m working on a Python pipeline with two quite different parts.
The first part is typical tabular data processing: joins, aggregations, cumulative calculations, and similar transformations.
The second part is sequential/recursive: within each time-ordered group, some values for the current row depend on the results computed for the previous week’s row. So this is not a purely vectorizable row-independent problem.
I’m not looking for code-specific debugging, but rather for architectural advice on the best way to handle this kind of workload efficiently
I’d like to improve performance, but I don’t want to start by assuming there is only one correct solution.
My question is: for a problem like this, which approaches or frameworks would you recommend evaluating?
I must use Python
r/Python • u/Lucky_Ad_976 • Apr 01 '26
I am a developer of Rhesis.ai, a solution for testing LLM applications. We have a FastAPI backend and a Celery worker. The system performs many external API calls, followed by numerous LLM API queries (e.g., OpenAI) to evaluate the outputs. This is a typical I/O-bound workload.
The question is: how can we parallelize this more effectively?
Currently, we use a Celery task to execute a set of tests. Within a single task, we use asyncio—for example, if a test set contains 50 tests, we send all 50 requests concurrently and then perform all 50 evaluation queries concurrently as well.
The issue is that the number of test sets processed concurrently is limited by the number of prefork worker processes in Celery. Increasing the number of processes increases RAM usage, which we want to avoid.
What we're looking for is a way to fully leverage async—i.e., a system where tasks can be continuously scheduled onto an event loop without being constrained by a fixed number of worker processes or threads. While the code inside a task is asynchronous, the tasks themselves are still effectively executed sequentially at the worker level.
FastAPI demonstrates the model we're aiming for—handling many concurrent requests on an event loop and scaling with multiple processes (e.g., via Gunicorn). However, it does not provide task queuing capabilities.
So what would you recommend? Ideally, we're looking for a library or architecture where each process runs an event loop, and incoming tasks are scheduled onto it and executed concurrently, without waiting for previously submitted tasks to complete (unlike Celery's current model).
We also considered Dramatiq, but it appears to have a similar limitation—tasks can use async internally, but are still executed sequentially at the worker level.
Finally, we'd prefer a solution that is stable and mature — something with a proven track record in production environments, active maintenance, and a reliable community behind it. We're not looking to adopt an experimental or early-stage library as a core part of our infrastructure.
r/Python • u/zubb999 • Apr 01 '26
I'm looking for a Python library that can do the following:
* Convert both XLSX and XLS files to CSV
* Can have some configurations with regards to customizing the delimiter (like | as opposed to ,)
* Can have configurations with regards to multiple tabs/sheets in the excel file (can combine all tabs into a single csv file or make each tab into a separate csv file)
And have backwards functionality
* Can convert CSV to XLSX or XLS
* Can have configurations with regards to using a custom delimiter
* Can have configurations with regards to combining multiple csv files into a single XLSX file (combine multiple csv's into a single excel tab or a separate excel tab for each csv file)
I'm sure there's a library that exists out there, I just wonder if someone could point me in the right direction as a starting point.
EDIT: Forgot to mention I did find out that Pandas at least does file conversion, but want sure if it could do the additional things. Also, I question if Pandas would be the fastest method for doing this, since it's not specialized for this.
Please keep up with responses, it's very helpful!!
r/Python • u/Western-Juice-3965 • Mar 31 '26
I recently revisited an older project I've built with a friend for a school project as part of the ESA Astro Pi 2024 challenge.
The idea was to estimate the speed of the ISS using only images of Earth.
The whole thing is implemented in Python using OpenCV.
Basic approach:
The result I got was around 7.47 km/s, while the actual ISS speed is about 7.66 km/s (~2–3% difference).
What My Project Does
It estimates the orbital speed of the ISS by analyzing displacement between features in consecutive images using computer vision.
Target Audience
This is mainly an educational / experimental project.
It’s not meant for production use, but for learning computer vision, image processing, and working with real-world data.
Comparison
Unlike typical examples or tutorials, this project applies feature detection and matching to a real-world problem (estimating ISS speed from images).
It combines multiple steps (feature detection, matching, displacement calculation, and physical conversion) into a complete pipeline instead of isolated examples.
One limitation: the original runtime images are lost, so the repo mainly contains test/template images.
Looking back, I’d definitely refactor parts of the code (especially matching/filtering) but the overall approach still works.
If anyone has suggestions on improving match quality or reducing noise/outliers, I’d be interested.
Repo:
r/Python • u/Immapillpopnanimal • Mar 31 '26
hey everyone. I wasn't sure if this should have been marked as a resource or discussion, but I was trying to buy a good book to learn coding and I came across Mark matthes and Eric Lutz's "Python crash course". but Google is telling me their is also two people named MARK LUTZ, and ERIC MATTHES who actually wrote their own
separate books? is this accurate? and if so, is one of them more reputable than the others? anyone who knows + any recommendations would be awesome. thanks in advance everyone.
r/Python • u/Simi_auto3 • Mar 31 '26
Hi everyone,
I’ve been working on Dynantic, a Python ORM for DynamoDB. The project started because I wanted to use Pydantic v2 models directly as database models in my FastAPI/Lambda stack, without the need to map them to proprietary ORM types (like PynamoDB attributes) or raw Boto3 dictionaries.
What My Project Does Dynantic is a synchronous-first ORM that maps Pydantic v2 models to DynamoDB tables. It handles all the complex Boto3 serialization and deserialization behind the scenes, allowing you to work with native Python types while ensuring data validation at the database level. It includes a DSL for queries, support for GSIs, and built-in handling for batch operations and transactions.
Core approach: Single Table Design & Polymorphism One of the main focuses of the library is how it handles multiple entities within a single table. Instead of manual parsing, it uses a discriminator pattern to automatically instantiate the correct subclass when querying the base table:
Python
from dynantic import DynamoModel, Key, Discriminator
class Asset(DynamoModel):
asset_id: str = Key()
type: str = Discriminator() # Auto-tracks the subclass type
class Meta:
table_name = "infrastructure"
@Asset.register("SERVER")
class Server(Asset):
cpu_cores: int
memory_gb: int
@Asset.register("DATABASE")
class Database(Asset):
engine: str
# When you scan or query, you get back the actual subclasses
for asset in Asset.scan():
if isinstance(asset, Server):
print(f"Server {asset.asset_id}: {asset.cpu_cores} cores")Key Technical Points:
Key(auto=True)) and automatic response pagination (cursor-based) for stateless APIs.Target Audience Dynantic is designed for developers building serverless backends with AWS Lambda and FastAPI who are looking for a "SQLModel-like" developer experience. It’s for anyone who wants to maintain a single source of truth for their data models across their API and database layers.
Comparison
AI Integration: You can also find a Claude Code Skill in the repository that helped me better using the library with llm. Since new libraries aren't in the training data of current LLMs, this skill provides coding agents with the context of the DSL and best practices, making it easier to generate valid models and queries.
The project is currently in Beta (0.3.1). I’d love to get some honest feedback on the API design or any rough edges you might find!
GitHub:https://github.com/Simi24/dynantic
PyPI: pip install dynantic
r/Python • u/No_Second1489 • Mar 31 '26
I've tried Bayan and Grobid-python so far, both are good enough but they mess up some part of the paper, either the title, or the keywords, or the references, I just want a tool that can correctly parse title, abstract, intro, conclusion and references, I don't need tables or equations or images.
r/Python • u/AutoModerator • Mar 31 '26
Dive deep into Python with our Advanced Questions thread! This space is reserved for questions about more advanced Python topics, frameworks, and best practices.
Let's deepen our Python knowledge together. Happy coding! 🌟
r/Python • u/helloerikaaa • Mar 30 '26
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 • u/not_afraid_of_trying • Mar 30 '26
Python should have been there for non-techi users. We should be able to distribute executables built by PyInstaller or Nuitka to family and friends. Small utilities that single-thing is great time saver for them. But you cannot do that. Because anti-virus will come and flag your binary. They will do everything to scare your users away. Away from Python ecosystem. Powershell, Dotnet, go, rust, C++ self-contained executables are fine - just python exes are bad for antivirus community, especially if you add icon to your exe.
This is really unfortunate. PyInstaller is such a beautiful tool that can empower so many people... only if anti-virus software does better job of detecting good vs. bad.
NOTE: An alternative is to effectively “bribe the system” by acquiring a code-signing certificate, a tactic reportedly used by attackers. Or make everything as a web app.
r/Python • u/Kale • Mar 30 '26
So, I know there's community "guidelines" for Python, like all caps are used for global variables, underscore in front of variables or methods for private variables/methods, etc.
I'm doing some message passing via Python Queues to make some stuff thread-safe. I need to check the message on the Queue to figure out what to do with it. I can either make a few dataclasses, or message using tuples with a string as the first element indicating the structure of the remaining elements.
Both methods would work, I'm asking more general consensus on if there's guidelines to follow, which is why I posted here for discussion. If this isn't the place I can move this question to another sub.
If it matters, I will probably be running this through Cython eventually. It's a little weird, but Cython does support dataclasses (by making them structs).
So, better to use:
if isinstance(msg,UpdateObject):
or:
if msg[0] == 'update':
?
r/Python • u/SirCypkowskyy • Mar 30 '26
I’ve tried starting a blog a few times before, but like many of us, I usually abandoned it. Recently, I felt the need to put together a new personal site, and this time I actually managed to deliver something.
I built https://gburek.dev from scratch using Next.js + Cloudflare Workers for that sweet serverless setup. I also made it fully bilingual (EN/PL).
My intent isn’t to write generic tutorials - actually, my goal is to focus on real-world programming, IT architecture, and AI - basically the stuff I actually deal with at work and in my own side projects. In the near future, I’m planning to launch a YouTube channel too!
Anyway, the main reason I’m posting is to share the first "serious" article I cooked up:
Why I use UV and Ruff in Python projects, and you should too - https://gburek.dev/en/blog/why-i-use-ruff
I used to complain *a lot* about working with Python and its tooling ecosystem, but these two tools entirely changed my perspective. If you've been frustrated with Python setups lately, give it a read.
We'll see how this whole blogging thing goes. I’d love to get some feedback from you guys -whether it's about the post itself, the site's performance, or the stack. Thanks in advance!
r/Python • u/Soft_Playful • Mar 30 '26
For the past ~5 years I’ve been doing a lot of repetitive operational tasks manually at work. Recently I started automating parts of the workflow using Python and the time savings honestly surprised me.
So far I’ve automated:
– sending transactions through a mobile app workflow
– opening an admin web panel
– navigating the admin web panel
– filling forms automatically
– submitting entries
Right now I’m working on automating the approval side of those entries as well.
I also regularly use Postman for API testing, recently started using Newman for running collections from the CLI, and have some experience using JMeter for performance testing.
This made me realize how much more operational work could probably be automated that I never explored before. I’d like to go deeper into Python-based automation and eventually move toward remote automation work.
What Python tools/libraries or types of automation projects would you recommend learning next to level up from here? What should I learn next ?
r/Python • u/GeometryDashGod • Mar 30 '26
I'm being serious, we need to take action against this. Every single post I've gotten in my feed from this subreddit has been an entirely AI generated project showcase. The posters usually generate the entire post, the app, their replies to comments, and literally everything in between with AI. What is the point of such a subreddit that is just full of AI slop? I propose we get a rule against AI slop in this subreddit.
r/Python • u/AutoModerator • Mar 30 '26
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.
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
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
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! 🌟
r/Python • u/ElDonSultan • Mar 29 '26
I got tired of watching Claude write WHERE status = 'active' when the column contains 'Active', then retry with 'enabled', then give up. Most Postgres MCP servers give agents query and list_tables and call it a day. The agent flies blind.
pglens has 27 read-only tools that let an agent understand your database before writing SQL. Zero config - reads standard PG* env vars, works on any Postgres 12+ (self-hosted, RDS, Aurora, whatever). Two dependencies: asyncpg and mcp.
Source: https://github.com/janbjorge/pglens
What My Project Does
The highlights:
Everything runs in readonly=True transactions, identifiers escaped via Postgres's own quote_ident(). No DDL tools exposed.
Target Audience
Anyone using an AI coding agent (Claude Code, Cursor, Windsurf, etc.) against PostgreSQL. I run it against production daily - read-only so it can't break anything. On PyPI, integration tested against real Postgres via testcontainers.
Comparison
pglens is PostgreSQL-only by design. Uses pg_catalog for everything, needs zero extensions.
pip install pglens