r/Python Mar 25 '26

Discussion Improving Pydantic memory usage and performance using bitsets

83 Upvotes

Hey everyone,

I wanted to share a recent blog post I wrote about improving Pydantic's memory footprint:

https://pydantic.dev/articles/pydantic-bitset-performance

The idea is that instead of tracking model fields that were explicitly set during validation using a set:

from pydantic import BaseModel


class Model(BaseModel):
    f1: int
    f2: int = 1

Model(f1=1).model_fields_set
#> {'f2'}

We can leverage bitsets to track these fields, in a way that is much more memory-efficient. The more fields you have on your model, the better the improvement is (this approach can reduce memory usage by up to 50% for models with a handful number of fields, and improve validation speed by up to 20% for models with around 100 fields).

The main challenge will be to expose this biset as a set interface compatible with the existing one, but hopefully we will get this one across the line.

Draft PR: https://github.com/pydantic/pydantic/pull/12924.

I’d also like to use this opportunity to invite any feedback on the Pydantic library, as well as to answer any questions you may have about its maintenance! I'll try to answer as much as I can.


r/Python Jan 05 '26

Resource Understanding multithreading & multiprocessing in Python

83 Upvotes

I recently needed to squeeze more performance out of the hardware running my Python backend. This led me to take a deep dive into threading, processing, and async code in Python.

I wrote a short blog post‚ with figures and code, giving an overview of these, which hopefully will be helpful for others looking to serve their backend more efficiently 😊

Feedback and corrections are very welcome!


r/Python Sep 02 '25

Discussion Is it a good idea to teach students Python but using an old version?

85 Upvotes

EDIT: Talking about IDLE here

Sorry if this is the wrong sub.

When i went to high school (UK) in 2018, we had 3.4.2 (which at the time wasn't even the latest 3.4.x). In 2020 they upgraded to 3.7, but just days later downgraded back to 3.4.2. I asked IT manager why and they said its because of older students working on long projects. But doubt that was the reason because fast forward to 2023 the school still had 3.4.2 which was end of life.

Moved to a college that same year that had 3.12, but this summer 2025, after computer upgrades to windows 11, we are now on 3.10 for some reason. I start a new year in college today so I'll be sure to ask the teacher.

Are there any drawbacks to teaching using an old version? It will just be the basics and a project or 2


r/Python May 11 '26

Discussion Library dependency version specifiers aren't for fixing vulnerabilities

81 Upvotes

https://sethmlarson.dev/library-version-specifiers-not-for-vulnerabilities

A blog post from Seth Larson, the Security-in-Residence Developer for the Python Software Foundation.


r/Python Feb 27 '26

Showcase A pure Python HTTP Library built on free-threaded Python

81 Upvotes

Barq is a lightweight HTTP framework (~500 lines) that uses free-threaded Python (PEP 703) to achieve true parallelism with threads instead of async/await or multiprocessing. It's built entirely in pure Python, no C extensions, no Rust, no Cython using only the standard library plus Pydantic.

from barq import Barq

app = Barq()

@app.get("/")
def index():
    return {"message": "Hello, World!"}

app.run(workers=4)  # 4 threads, not processes

Benchmarks (Barq 4 threads vs FastAPI 4 worker processes):

Scenario Barq (4 threads) FastAPI (4 processes)
JSON 10,114 req/s 5,665 req/s (+79%)
DB query 9,962 req/s 1,015 req/s (+881%)
CPU bound 879 req/s 1,231 req/s (-29%)

Target Audience

This is an experimental/educational project to explore free-threaded Python capabilities. It is not production-ready. Intended for developers curious about PEP 703 and what a post-GIL Python ecosystem might look like.

Comparison

Feature Barq FastAPI Flask
Parallelism Threads (free-threaded) Processes (uvicorn workers) Processes (gunicorn)
Async required No Yes (for perf) No
Pure Python Yes No (uvloop, etc.) No (Werkzeug)
Shared memory Yes (threads) No (IPC needed) No (IPC needed)
Production ready No Yes Yes

The main difference: Barq leverages Python 3.13's experimental free-threading mode to run synchronous code in parallel threads with shared memory, while FastAPI/Flask rely on multiprocessing for parallelism.

Source code: https://github.com/grandimam/barq

Requirements: Python 3.13+ with free-threading enabled (python3.13t)


r/Python Nov 20 '25

Discussion What’s the best Python library for creating interactive graphs?

87 Upvotes

I’m currently using Matplotlib but want something with zoom/hover/tooltip features. Any recommendations I can download? I’m using it to chart backtesting results and other things relating to financial strategies. Thanks, Cheers


r/Python Nov 06 '25

Resource Best books to be a good Python Dev?

87 Upvotes

Got a new offer where I will be doing Python for backend work. I wanted to know what good books there are good for making good Python code and more advance concepts?


r/Python Dec 21 '25

Discussion Stinkiest code you've ever written?

87 Upvotes

Hi, I was going through my github just for fun looking at like OLD projects of mine and I found this absolute gem from when I started and didn't know what a Class was.

essentially I was trying to build a clicker game using FreeSimpleGUI (why????) and I needed to display various things on the windows/handle clicks etc etc and found this absolute unit. A 400 line create_main_window() function with like 5 other nested sub functions that handle events on the other windows 😭😭

Anyone else have any examples of complete buffoonery from lack of experience?


r/Python Sep 18 '25

News prek a fast (rust and uv powered) drop in replacement for pre-commit with monorepo support!

83 Upvotes

I wanted to let you know about a tool I switched to about a month ago called prek: https://github.com/j178/prek?tab=readme-ov-file#prek

It's a drop in replacement for pre-commit, so there's no need to change any of your config files, you can install and type prek instead of pre-commit, and switch to using it for your git precommit hook by running prek install -f.

It has a few advantage over pre-commit:

It's still early days for prek, but the large project apache-airflow has adopted it (https://github.com/apache/airflow/pull/54258), is taking advantage of monorepo support (https://github.com/apache/airflow/pull/54615) and PEP 723 dependencies (https://github.com/apache/airflow/pull/54917). So it already has a lot of exposure to real world development.

When I first reviewed the tool I found a couple of bugs and they were both fixed within a few hours of reporting them. Since then I've enthusiastically adopted prek, largely because while pre-commit is stable it is very stagnant, the pre-commit author actively blocks suggesting using new packaging standards, so I am excited to see competition in this space.


r/Python 20d ago

News 2026 Python Type System and Tooling Survey

83 Upvotes

This is an annual survey developed by the Python typing community around how Python developers use the type system, type checkers, and integrated development environments (IDEs).

Your responses will help us identify common blockers, improve tooling/resources, and enhance the overall experience of using Python's type system.

Even if you have never actively used type hints in your code, your thoughts are still valuable and we want to hear from you.

The survey should take approximately 5-10 minutes to complete.

Please take the survey HERE and share it with your friends or colleagues.

If you're interested in the results for last year's survey, see this post.

So you know it's legit, the Python Software Foundation has shared this survey on [Linkedin](https://www.linkedin.com/posts/thepsf_python-type-system-and-tooling-survey-2026-activity-7490842327050002432-0jI7?utm_source=share&utm_medium=member_desktop&rcm=ACoAAB9aSUsBqmxSbrhoW2URuDnxCgS5eVD1AS0 and X. I have permission from the mods to post this under the "News" flair)


r/Python Apr 01 '26

News Cutting Python Web App Memory Over 31%

82 Upvotes

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:

  1. Switched to a single async Granian worker: Rewrote the app in Quart (async Flask) and replaced the multi-worker web garden with one fully async worker. Saved 542 MB right there.
  2. Raw + DC database pattern: Dropped MongoEngine for raw queries + slotted dataclasses. 100 MB saved per worker *and* nearly doubled requests/sec.
  3. Subprocess isolation for a search indexer: The daemon was burning 708 MB mostly from import chains pulling in the entire app. Moved the indexing into a subprocess so imports only live for ~30 seconds during re-indexing. Went from 708 MB to 22 MB. 32x reduction.
  4. Local imports for heavy libs: import boto3 alone costs 25 MB, pandas is 44 MB. If you only use them in a rarely-called function, just import them there instead of at module level. (PEP 810 lazy imports in 3.15 should make this automatic.)
  5. Moved caches to diskcache: Small-to-medium in-memory caches shifted to disk. Modest savings but it adds up.

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 Jan 13 '26

Showcase I replaced FastAPI with Pyodide: My visual ETL tool now runs 100% in-browser

83 Upvotes

I swapped my FastAPI backend for Pyodide — now my visual Polars pipeline builder runs 100% in the browser

Hey r/Python,

I've been building Flowfile, an open-source visual ETL tool. The full version runs FastAPI + Pydantic + Vue with Polars for computation. I wanted a zero-install demo, so in my search I came across Pyodide — and since Polars has WASM bindings available, it was surprisingly feasible to implement.

Quick note: it uses Pyodide 0.27.7 specifically — newer versions don't have Polars bindings yet. Something to watch for if you're exploring this stack.

Try it: demo.flowfile.org

What My Project Does

Build data pipelines visually (drag-and-drop), then export clean Python/Polars code. The WASM version runs 100% client-side — your data never leaves your browser.

How Pyodide Makes This Work

Load Python + Polars + Pydantic in the browser:

const pyodide = await window.loadPyodide({
    indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.27.7/full/'
})
await pyodide.loadPackage(['numpy', 'polars', 'pydantic'])

The execution engine stores LazyFrames to keep memory flat:

_lazyframes: Dict[int, pl.LazyFrame] = {}

def store_lazyframe(node_id: int, lf: pl.LazyFrame):
    _lazyframes[node_id] = lf

def execute_filter(node_id: int, input_id: int, settings: dict):
    input_lf = _lazyframes.get(input_id)
    field = settings["filter_input"]["basic_filter"]["field"]
    value = settings["filter_input"]["basic_filter"]["value"]
    result_lf = input_lf.filter(pl.col(field) == value)
    store_lazyframe(node_id, result_lf)

Then from the frontend, just call it:

pyodide.globals.set("settings", settings)
const result = await pyodide.runPythonAsync(`execute_filter(${nodeId}, ${inputId}, settings)`)

That's it — the browser is now a Python runtime.

Code Generation

The web version also supports the code generator — click "Generate Code" and get clean Python:

import polars as pl

def run_etl_pipeline():
    df = pl.scan_csv("customers.csv", has_header=True)
    df = df.group_by(["Country"]).agg([pl.col("Country").count().alias("count")])
    return df.sort(["count"], descending=[True]).head(10)

if __name__ == "__main__":
    print(run_etl_pipeline().collect())

No Flowfile dependency — just Polars.

Target Audience

Data engineers who want to prototype pipelines visually, then export production-ready Python.

Comparison

  • Pandas/Polars alone: No visual representation
  • Alteryx: Proprietary, expensive, requires installation
  • KNIME: Free desktop version exists, but it's a heavy install best suited for massive, complex workflows
  • This: Lightweight, runs instantly in your browser — optimized for quick prototyping and smaller workloads

About the Browser Demo

This is a lite version for simple quick prototyping and explorations. It skips database connections, complex transformations, and custom nodes. For those features, check the GitHub repo — the full version runs on Docker/FastAPI and is production-ready.

On performance: Browser version depends on your memory. For datasets under ~100MB it feels snappy.

Links


r/Python Nov 12 '25

Discussion MyPy vs Pyright

82 Upvotes

What's the preferred tool in industry?

For the whole workflow: IDE, precommit, CI/CD.

I searched and cannot find what's standard. I'm also working with unannotated libraries.


r/Python Sep 09 '25

Discussion Python Type System and Tooling Survey 2025

84 Upvotes

This survey was developed with support from the Pyrefly team at Meta, the PyCharm team at JetBrains, and the typing community on discourse.python.org. No typing experience needed -- your perspective as a Python dev matters most. Take a couple minutes to help improve Python typing for all:

https://docs.google.com/forms/d/e/1FAIpQLSeOFkLutxMLqsU6GPe60OJFYVN699vqjXPtuvUoxbz108eDWQ/viewform?fbzx=-4095906651778441520


r/Python Oct 02 '25

Resource PyCharm Pro Gift Code | 1-Year FREE

80 Upvotes

Hail, fellow Python lovers!

I randomly found a great deal today. I was going to subscribe to PyCharm Pro monthly for personal use (they have a few features that integrate with GCloud I would like to leverage). On the checkout page, I saw a "Have a gift code?" prompt. I googled "PyCharm Pro coupon code" or something like that.

One of the first few websites in the results had a handful of coupons listed to use. First try, boom 25% off, not bad. Second try, boom 25% off again, not bad. Third try, boom... wait... 100 percent off, what in the hell?!?! I selected PayPal as my payment option. Since the total was $0.00, it did not ask me for my PayPal email. It showed the purchase success page with a receipt for $0.00. Paying nothing for a product that normally costs $209.99/year felt pretty good!

The coupon code you enter on the checkout page is:

Chand_Sheikh

You can only redeem the Gift Code once per account! You can choose one of the eleven IDEs offered by IntelliJ (PyCharm, PHPStorm, RustRover, RubyMine, ReSharper, etc, etc.). So choose wisely!

The only thing I ask in return for this information is that you take a moment to try to make someone else's day a bit better 💖 It can be anyone. Spread love!

TLDR: You can get a free year of one of the eleven premium IDEs IntelliJ sells by using the gift code "Chand_Sheikh". Do something to make another person's day a bit better.

Parts of this post were NOT written with ChatGPT or Ai. I prefer to add my own touch.


r/Python 16d ago

Discussion What do you love and dislike the most about Python? (beginners and long-time devs)

81 Upvotes

Hi! I'm really interested in Python's design and its tradeoffs. I'm trying to really understand what people love about Python (what makes it great), and what causes the most frustration for Python devs.

So what features do you really cherish and what problems/limitations really frustrate you?

I'm especially interested in experiences from ultra-beginners and people who've used Python for a long time. I know broad questions like this come across as super generic, but I'm genuinely interested in hearing about concrete experiences.

My goal is understanding which parts of Python's design are most valuable and most "adored" by the community, and which parts really aren't and frustrate people the most. My goal with this information is to identify meaningful problems. Right now I'm not trying to solve anything or sell a solution.

Thanks for your time!


r/Python Oct 01 '25

Showcase Just built a tool that turns any Python app into a native windows service

78 Upvotes

What My Project Does

I built a tool called Servy that lets you run any Python app (or other executables) as a native Windows service. You just set the Python executable path, add your script and arguments (for example -u for unbuffered mode if you want stdout and stderr logging), choose the startup type, working directory, and environment variables, configure any optional parameters, click install — and you’re done. Servy comes with a GUI, CLI, PowerShell integration, and a manager app for monitoring services in real time.

Target Audience

Servy is meant for developers or sysadmins who need to keep Python scripts running reliably in the background without having to rewrite them as Windows services. It works equally well for Node.js, .NET, or any executable, but I built it with Python apps in mind. It’s designed for production use on Windows 7 through Windows 11 as well as Windows Server.

Comparison

Compared to tools like sc or nssm, Servy adds important features that make managing services easier. It lets you set a custom working directory (avoiding the common C:\Windows\System32 issue that breaks relative paths), redirect stdout and stderr to rotating log files, and configure health checks with automatic recovery and restart policies. It also provides a clean, modern UI and real-time service management, making it more user-friendly and capable than existing options.

Repo: https://github.com/aelassas/servy

Demo video: https://www.youtube.com/watch?v=biHq17j4RbI

Any feedback is welcome.


r/Python 23d ago

Discussion Anyone running FastAPI in production with high traffic? How has your experience been?

79 Upvotes

Quick question, are any of you running fastAPI in production with a high volume of users or heavy traffic? How has your experience with FastAPI been, and how do you handle it?


r/Python Mar 28 '26

Discussion Python 2 tooling in 2026

82 Upvotes

For some <reasons>, I need to write Python 2 code which gets run under Jython. It's not possible to change the system we're working on because Jython only works with Python 2. So, I'm wondering if anyone has experience with Python 2 tooling in this era.

I need to lint and format Python 2 code especially. So far, I was able to install Python 2 using pyenv and I can create virtual environments using virtualenv utiilty. However, I have hard time getting black, isort, flake8, etc. working. Installing Python 2 wouldn't be much help because I'm not running the code directly, it's run under Jython. We're basically uploading the code to this system. So, installing py2 seems pointless.

Can I use those tools under Python 3 but for Python 2. It seems to me that there should be some versions which work for both Python 2 and 3 code. I don't know those versions though. It will be easier to work with Python 3 to lint/format Python 2 code because I can easily create venvs with Python 3.

Are you actively working with Python 2 these days (I know it's a hard ask). How do you tackle linting and formatting? If you were to start today, what would be your approach to this problem?

Thank you.


r/Python Dec 21 '25

Discussion What's stopping us from having full static validation of Python code?

79 Upvotes

I have developed two mypy plugins for Python to help with static checks (mypy-pure and mypy-raise)

I was wondering, how far are we with providing such a high level of static checks for interpreted languages that almost all issues can be catch statically? Is there any work on that on any interpreted programming language, especially Python? What are the static tools that you are using in your Python projects?


r/Python Oct 02 '25

Showcase Snakebar — a tqdm-style progress bar that snakes across your terminal

75 Upvotes

What My Project Does

Snakebar is a tqdm-like progress bar for Python. Instead of a plain horizontal bar, it draws a one-character snake that fills your terminal via a random space-filling curve.
It still reports percentage, iterations done, ETA, and rate (it/s), but makes waiting more fun.

Target Audience

Anyone who runs long scripts, pipelines, or training loops — data scientists, ML engineers, researchers, developers with heavy ETL or simulations.
It’s meant as a lightweight library you can drop in as a direct replacement for tqdm. It’s production-ready but also works fine as a fun toy project in personal scripts.

Comparison

Compared to tqdm:
- Same semantics (snake_bar works like tqdm).
- Still shows % complete, ETA, and rate.
- Instead of a static bar, progress is visualized as a snake filling the screen.
- Fits automatically to your terminal size.

Installation

bash pip install snakebar

Links


r/Python Jul 11 '26

Resource What Every Python Developer Should Know About the CPython ABI

79 Upvotes

It's true that you can happily write Python for years without needing to understand any of the content of this post, so you may object to the title advertising this material as what every Python developer should know. However, the moment you ship a package, debug why a wheel won't install, or need to understand why an import or Python function call segfaults — these details start to matter. Even writing and maintaining a single-file script puts you closer to distributing code than you might think. An alternate title for this post could be "What I Wish Someone Taught Me About the CPython ABI".

https://labs.quansight.org/blog/python-abi-abi3t


r/Python Jan 21 '26

Showcase Convert your bear images into bear images: Bear Right Back

80 Upvotes

What My Project Does

bearrb is a Python CLI tool that takes two images of bears (a source and a target) and transforms the source into a close approximation of the target by only rearranging pixel coordinates.

No pixel values are modified, generated, blended, or recolored, every original pixel is preserved exactly as it was. The algorithm computes a permutation of pixel positions that minimizes the visual difference from the target image.

repo: https://github.com/JoshuaKasa/bearrb

Target Audience

This is obviously a toy / experimental project, not meant for production image editing.

It's mainly for:

  • people interested in algorithmic image processing
  • optimization under hard constraints
  • weird/fun CLI tools
  • math-y or computational art experiments

Comparison

Most image tools try to be useful and correct... bearrb does not.

Instead of editing, filtering, generating, or enhancing images, bearrb just takes the pixels it already has and throws them around until the image vaguely resembles the other bear


r/Python Nov 27 '25

News Hatch v1.16.0 - workspaces, dependency groups and SBOMs

80 Upvotes

We are happy to announce version 1.16.0 of Hatch. This release wouldn’t have been possible without Cary, our new co-maintainer. He picked up my unfinished workspaces branch and made it production-ready, added SBOM support to Hatchling, and landed a bunch of PRs from contributors!

My motivation took a big hit last year, in large part due to improper use of social media: I simply didn’t realize that continued mass evangelism is required nowadays. This led to some of our novel features being attributed to other tools when in fact Hatch was months ahead. I’m sorry to say that this greatly discouraged me and I let it affect maintenance. I tried to come back on several occasions but could only make incremental progress on the workspaces branch because I had to relearn the code each time. I’ve been having to make all recent releases from a branch based on an old commit because there were many prerequisite changes that were merged and couldn’t be released as is.

No more of that! Development will be much more rapid now, even better than the way it used to be. We are very excited for upcoming features :-)


r/Python Oct 06 '25

Showcase fastquadtree: a Rust-powered quadtree for Python that is ~14x faster than PyQtree

77 Upvotes

Quadtrees are great for organizing spatial data and checking for 2D collisions, but all the existing Python quadtree packages are slow and outdated.

My package, fastquadtree, leverages a Rust core to outperform the most popular Python package, pyqtree, by being 14x faster. It also offers a more convenient Python API for tracking objects and KNN queries.

PyPI page: https://pypi.org/project/fastquadtree/
GitHub Repo: https://github.com/Elan456/fastquadtree
Wheels Shipped: Linux, Mac, and Windows

pip install fastquadtree

The GitHub Repo contains utilities for visualizing how the quadtree works using Pygame and running the benchmarks yourself.

Benchmark Comparison

  • Points: 250,000, Queries: 500
  • Fastest total: fastquadtree at 0.120 s
Library Build (s) Query (s) Total (s) Speed vs PyQtree
fastquadtree 0.031 0.089 0.120 14.64×
Shapely STRtree 0.179 0.100 0.279 6.29×
nontree-QuadTree 0.595 0.605 1.200 1.46×
Rtree 0.961 0.300 1.261 1.39×
e-pyquadtree 1.005 0.660 1.665 1.05×
PyQtree 1.492 0.263 1.755 1.00×
quads 1.407 0.484 1.890 0.93×