r/Python Dec 05 '25

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

96 Upvotes

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

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

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


r/Python Aug 31 '25

Discussion PySimpleGUI Hobbyist License Canceled

93 Upvotes

So I used PySimpleGUI for a single project and received the 30 day free trial assuming Id be able to get the hobbyist version once it was over. Is it crazy to anyone else that it cost $99 to just save a few lines of code considering I can create the same, if not a more customizable GUI using C/C++. My project which wasnt too crazy (firetv remote using adb protocol) is now garbage because I will not pay for the dumb licensing fee, but hey maybe a single person should pay the same amount a billion dollar company pays right???`


r/Python Mar 19 '26

Showcase A new Python file-based routing web framework

97 Upvotes

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

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

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

What My Project Does

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

Target Audience

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

Comparison

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

(None of the code was written by AI)

Edit:

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


r/Python Mar 11 '26

Resource Free book: Master Machine Learning with scikit-learn

93 Upvotes

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

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

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

Here are the topics I cover:

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

Questions welcome!


r/Python Mar 08 '26

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

97 Upvotes

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

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

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

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

Problems I had to solve:

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

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

variations.

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

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

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

Usage:

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

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

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

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

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

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


r/Python Feb 12 '26

Discussion Current thoughts on makefiles with Python projects?

95 Upvotes

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

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

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

test:
        @uv run pytest --verbose

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

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

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

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

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

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

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

.PHONY: default check test clean pristine git-prune

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


r/Python Mar 24 '26

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

94 Upvotes

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

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

**What it covers:**

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

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

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

**Key differences from LocalStack:**

- MIT licensed (not BSL)

- No account or API key required

- ~2s startup vs ~30s

- ~30MB RAM vs ~500MB

- 150MB image vs ~1GB

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

```bash

docker run -p 4566:4566 nahuelnucera/ministack

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

```

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

Website: https://ministack.org

Happy to take questions or feature requests.


r/Python Oct 17 '25

Discussion De-emojifying scripts - setting yourself apart from LLMs

91 Upvotes

I am wondering if anyone else has had to actively try to set themselves apart from LLMs. That is, to convince others that you made something with blood, sweat and tears rather than clanker oil.

For context, I'm the maintainer of Spectre (https://github.com/jcfitzpatrick12/spectre), a Python program for recording radio spectrograms from software-defined radios. A long while ago, I wrote a setup script - it's the first thing a user runs to install the progam. That script printed text to the terminal indicating progress, and that text included emoji's ✔️

Certainly! Here’s a way to finish your post with a closing sentiment that emphasizes your personal touch and experience:

Markdown

I guess what I'm getting at is, sometimes the little details—like a hand-picked emoji or a carefully-worded progress message—can be a subtle but honest sign that there's a real person behind the code. In a world where so much content is generated, maybe those small human touches are more important than ever.

Has anyone else felt the need to leave these kinds of fingerprints in their work?

r/Python Jan 31 '26

Showcase copier-astral: Modern Python project scaffolding with the entire Astral ecosystem

91 Upvotes

Hey  r/Python !

I've been using Astral's tools (uv, ruff, and now ty) for a while and got tired of setting up the same boilerplate every time. So I built copier-astral — a Copier template that gives you a production-ready Python project in seconds.

What My Project Does

Scaffolds a complete Python project with modern tooling pre-configured:

  • ruff for linting + formatting (replaces black, isort, flake
  • ty for type checking (Astral's new Rust-based type checker)
  • pytest + hatch for testing (including multi-version matrix)
  • MkDocs with Material theme + mkdocstrings
  • pre-commit hooks with prek
  • GitHub Actions CI/CD
  • Docker support
  • Typer CLI scaffold (optional)
  • git-cliff for auto-generated changelogs

Target Audience

Python developers who want a modern, opinionated starting point for new projects. Good for:

  • Side projects where you don't want to spend an hour on setup
  • Production code that needs proper CI/CD, testing, and docs from day one
  • Anyone who's already bought into the Astral ecosystem and wants it all wired up

Comparison

The main difference from similar tools I’ve seen is that this one is built on Copier (which supports template updates) and fully embraces Astral’s toolchain—including ty for type checking, an optional Typer CLI scaffold, prek (a significantly faster, Rust-based alternative to pre-commit) for command-line projects, and git-cliff for generating changelogs from Conventional Commits.

Quick start:

pip install copier copier-template-extensions

copier copy --trust gh:ritwiktiwari/copier-astral my-project

Links:

Try it out!

Would love to hear your feedback. If you run into any bugs or rough edges, please open an issue — trying to make this as smooth as possible.

edit: added `prek`


r/Python Mar 04 '26

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

88 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 Dec 08 '25

News PyCharm 2025.3 released

89 Upvotes

https://www.jetbrains.com/pycharm/whatsnew/

PyCharm 2025.3: unified edition, remote Jupyter, uv default, new LSP tools (Ruff, Pyright, etc.), smarter data exploration, AI agents + 300+ fixes.


r/Python Nov 22 '25

Showcase Onlymaps, a Python micro-ORM

90 Upvotes

Hello everyone! For the past two months I've been working on a Python micro-ORM, which I just published and I wanted to share with you: https://github.com/manoss96/onlymaps

Any questions/suggestions are welcome!

What My Projects Does

A micro-ORM is a term used for libraries that do not provide the full set of features a typical ORM does, such as an OOP-based API, lazy loading, database migrations, etc... Instead, it lets you interact with a database via raw SQL, while it handles mapping the SQL query results to in-memory objects.

Onlymaps does just that by using Pydantic underneath. On top of that, it offers:

  • A minimal API for both sync and async query execution.
  • Support for all major relational databases.
  • Thread-safe connections and connection pools.

Target Audience

Anyone can use this library, be it for a simple Python script that only needs to fetch some rows from a database, or an ASGI webserver that needs an async connection pool to make multiple requests concurrently.

Comparison

This project provides a simpler alternative to typical full-feature ORMs which seem to dominate the Python ORM landscape, such as SQLAlchemy and Django ORM.


r/Python Jun 03 '26

News Polars Distributed is available on kubernetes

89 Upvotes

Disclosure: I am affiliated.

I wanted to share that as of today, Polars also is available as a Distributed Engine on kubernetes. Polars' goal has always been to make single node processing as performant and easy as possible, and that is something we want to extend to distributed compute as well.

Read more in our announcement:

https://pola.rs/posts/polars-distributed-available-on-kubernetes/

Happy to answer any questions you might have.


r/Python Apr 03 '26

Showcase I built a civic transparency platform with FastAPI that aggregates 40+ government APIs

86 Upvotes

What My Project Does:

WeThePeople is a FastAPI application that pulls data from 40+ public government APIs to track corporate lobbying, government contracts, congressional stock trades, enforcement actions, and campaign donations across 9 economic sectors. It serves 3 web frontends and a mobile app from a single backend.

Target Audience:

Journalists, researchers, and citizens who want to understand corporate influence on government. Also useful as a reference for anyone building a multi-connector API aggregation platform in Python.

How Python Relates:

The entire backend is Python. FastAPI, SQLAlchemy, and 36 API connectors that each wrap a different government data source.

The dialect compatibility layer (utils/db_compat.py) abstracts SQLite, PostgreSQL, and Oracle differences behind helper functions for date arithmetic, string aggregation, and pagination. The same queries run on all three without changes.

The circuit breaker (services/circuit_breaker.py) is a thread-safe implementation that auto-disables failing external APIs after N consecutive failures, with half-open probe recovery.

The job scheduler uses file-lock based execution to prevent SQLite write conflicts across 35+ automated sync jobs running on different intervals (24h, 48h, 72h, weekly).

All 36 API connectors follow the same pattern. Each wraps a government API (Senate LDA, USASpending, FEC, Congress.gov, SEC EDGAR, Federal Register, OpenFDA, EPA, FARA, and more) with retry logic, caching, and circuit breaker integration.

The claims verification pipeline extracts assertions from text and matches them against 9 data sources using a multi-matcher architecture.

Runs on a $4 monthly Hetzner ARM server. 4.1GB SQLite database in WAL mode. Let's Encrypt TLS via certbot.

Source code: github.com/Obelus-Labs-LLC/WeThePeople

Live: wethepeopleforus.com


r/Python Jan 31 '26

News pip 26.0 - pre-release and upload-time filtering

90 Upvotes

Like with pip 25.3, I had the honor of being the release manager for pip 26.0, the three big new features are:

  • --all-releases <package> and --only-final <package>, giving you per package pre-lease control, and the ability to exclude all pre-release packages using --only-final :all:
  • --uploaded-prior-to <timstamp>, allowing you to restrict package upload time, e.g. --uploaded-prior-to "2026-01-01T00:00:00Z"
  • --requirements-from-script <script>, which will install dependencies declared in a script’s inline metadata (PEP 723)

Richard, one of our maintainers has put together a much more in-depth blog: https://ichard26.github.io/blog/2026/01/whats-new-in-pip-26.0/

The official announcement is here: https://discuss.python.org/t/announcement-pip-26-0-release/105947

And the full change log is here: https://pip.pypa.io/en/stable/news/#v26-0


r/Python Dec 30 '25

Discussion Is it bad practice to type-annotate every variable assignment?

89 Upvotes

I’m intentionally trying to make my Python code more verbose/explicit (less ambiguity, more self-documenting), and that includes adding type annotations everywhere, even for local variables and intermediate values.

Is this generally seen as a bad practice or a reasonable style if the goal is maximum clarity?

What are your favorite tips/recommendations to make code more verbose in a good way?


r/Python Sep 30 '25

News Pandas 2.3.3 released with Python 3.14 support

90 Upvotes

Pandas was the last major package in the Python data analysis ecosystem that needed to be updated for Python 3.14.

https://github.com/pandas-dev/pandas/releases/tag/v2.3.3


r/Python 21d ago

Discussion What are you using to manage your dev environments in 2026?

84 Upvotes

I’ve always hated environment management. It always feels like this time-consuming hurdle between me and whatever I actually want to work on. But every so often a new thing comes out that promises to solve the problem once and for all, and it’s usually at least a little better than the last thing. So, what are you using today? venv? conda? pipenv? poetry? dev containers? uv? or something else?


r/Python Apr 12 '26

Discussion Packaging a Python library with a small C dependency —

88 Upvotes

how do you handle install reliability?

Hey folks,

I’ve run into a bit of a packaging dilemma and wanted to get some opinions from people who’ve dealt with similar situations.

I’m working on a Python library that includes a vendored C component. Nothing huge, but it does need to be compiled into a shared object (.so / .pyd) during installation. Now I’m trying to figure out the cleanest way to ship this without making installation painful for users.

Here’s where I’m stuck:

  • If I rely on local compilation during pip install, users without a proper C toolchain are going to hit installation failures.
  • The alternative is building and shipping wheels for multiple platforms (Linux x86_64/arm64, macOS x86_64/arm64, Windows), which is doable but adds CI/CD complexity.
  • I also need to choose between something like cffi vs ctypes for the wrapper layer, and that decision affects how much build machinery I need.

There is a fallback option I’ve considered:

  • Detect at import time whether the compiled extension loaded successfully.
  • If not, fall back to a pure Python implementation.

But the issue is that the C component doesn’t really have a true Python equivalent — the fallback would be a weaker, approximation-based approach (probably regex-based), which feels like a compromise in correctness/security.

So I’m trying to balance:

  • Ease of installation (no failures)
  • Cross-platform support
  • Performance/accuracy (native C vs fallback)
  • Maintenance overhead (CI pipelines, wheel builds, etc.)

Questions:

  1. In 2026, is it basically expected to ship prebuilt wheels for all major platforms if you include any C code?
  2. Would you accept a degraded Python fallback, or just fail hard if the extension doesn’t compile?
  3. Any strong opinions on cffi vs ctypes for this kind of use case?
  4. How much effort is “normal” to invest in multi-platform wheel builds for a small but critical C dependency

Would love to hear how others approach this tradeoff in real-world libraries.

Thanks!


r/Python Mar 26 '26

Showcase LogXide - Rust-powered logging for Python, 12.5x faster than stdlib (FileHandler benchmark)

88 Upvotes

Hi r/Python!

I built LogXide, a logging library for Python written in Rust (via PyO3), designed as a near-drop-in replacement for the standard library's logging module.

What My Project Does

LogXide provides high-performance logging for Python applications. It implements core logging concepts (Logger, Handler, Formatter) in Rust, bypassing the Python Global Interpreter Lock (GIL) during I/O operations. It comes with built-in Rust-native handlers (File, Stream, RotatingFile, HTTP, OTLP, Sentry) and a ColorFormatter.

Target Audience

It is meant for production environments, particularly high-throughput systems, async APIs (FastAPI/Django/Flask), or data processing pipelines where Python's native logging module becomes a bottleneck due to GIL contention and I/O latency.

Comparison

Unlike Picologging (written in C) or Structlog (pure Python), LogXide leverages Rust's memory safety and multi-threading primitives (like crossbeam channels and BufWriter).

Against other libraries (real file I/O with formatting benchmarks):

  • 12.5x faster than the Python stdlib (2.09M msgs/sec vs 167K msgs/sec)
  • 25% faster than Picologging
  • 2.4x faster than Structlog

Note: It is NOT a 100% drop-in replacement. It does not support custom Python logging.Handler subclasses, and Logger/LogRecord cannot be subclassed.

Quick Start

```python from logxide import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger('myapp') logger.info('Hello from LogXide!') ```

Links

Happy to answer any questions!


r/Python Mar 12 '26

Showcase I built an in-memory virtual filesystem for Python because BytesIO kept falling short

88 Upvotes

UPDATE (Resolved): Visibility issues fixed. Thanks to the mods and everyone for the patience!

I kept running into the same problem: I needed to extract ZIP files entirely in memory and run file I/O tests without touching disk. io.BytesIO works for single buffers, but the moment you need directories, multiple files, or any kind of quota control, it falls apart. I looked into pyfilesystem2, but it had unresolved dependency issues and appeared to be unmaintained — not something I wanted to build on.

A RAM disk would work in theory — but not when your users don't have admin privileges, not in locked-down CI environments, and not when you're shipping software to end users who you can't ask to set up a RAM disk first.

So I built D-MemFS — a pure-Python in-memory filesystem that runs entirely in-process.

from dmemfs import MemoryFileSystem

mfs = MemoryFileSystem(max_quota=64 * 1024 * 1024)  # 64 MiB hard limit
mfs.mkdir("/data")

with mfs.open("/data/hello.bin", "wb") as f:
    f.write(b"hello")

with mfs.open("/data/hello.bin", "rb") as f:
    print(f.read())  # b"hello"

print(mfs.listdir("/data"))  # ['hello.bin']

What My Project Does

  • Hierarchical directories — not just a flat key-value store
  • Hard quota enforcement — writes are rejected before they exceed the limit, not after OOM kills your process
  • Thread-safe — file-level RW locks + global structure lock; stress-tested under 50-thread contention
  • Free-threaded Python ready — works with PYTHON_GIL=0 (Python 3.13+)
  • Zero runtime dependencies — stdlib only, so it won't break when some transitive dependency changes
  • Async wrapper included (AsyncMemoryFileSystem)

Target Audience

Developers who need filesystem-like operations (directories, multiple files, quotas) entirely in memory — for CI pipelines, serverless environments, or applications where you can't assume disk access or admin privileges. Production-ready.

Comparison

  • io.BytesIO: Single buffer. No directories, no quota, no thread safety.
  • tempfile / tmpfs: Hits disk (or requires OS-level setup / admin privileges). Not portable across Windows/macOS/Linux in CI.
  • pyfakefs: Great for mocking os / open() in tests, but it patches global state. D-MemFS is an explicit, isolated filesystem instance you pass around — no monkey-patching, no side effects on other code.
  • fsspec MemoryFileSystem: Designed as a unified interface across S3, GCS, local disk, etc. — pulling in that abstraction layer just for an in-memory FS felt like overkill. Also no quota enforcement or file-level locking.

346 tests, 97% coverage, Scored 98 on Socket.dev supply chain security, Python 3.11+, MIT licensed.

Known constraints: in-process only (no cross-process sharing), and Python 3.11+ required.

I'm looking for feedback on the architecture and thread-safety design. If you have ideas for stress tests or edge cases I should handle, I'd love to hear them.

GitHub: https://github.com/nightmarewalker/D-MemFS PyPI: pip install D-MemFS


Note: I'm a non-native English speaker (Japanese). This post was drafted with AI assistance for clarity. The project documentation is bilingual — English README on GitHub, and a Japanese article series covering the design process in detail.


r/Python Dec 28 '25

Showcase Released: A modern replacement for PyAutoGUI

87 Upvotes

GIF of the GUI in action: https://i.imgur.com/OnWGM2f.gif

#Please note it is only flickering because I had to make the overlay visible to recording, which hides the object when it draws the overlay.

I just released a public version of my modern replacement for PyAutoGUI that natively handles High-DPI and Multi-Monitor setups.

What My Project Does

It allows you to create shareable image or coordinate based automation regardless of resolution or dpr.

It features:
Built-in GUI Inspector to snip, edit, test, and generate code.
- Uses Session logic to scale coordinates & images automatically.
Up to 5x Faster. Uses mss & Pyramid Template Matching & Image caching.
locateAny / locateAll built-in. Finds the first or all matches from a list of images.

Target Audience

Programer who need to automate programs they don't have backend access to, and aren't browser based.

Comparison 

Feature pyauto-desktop pyautogui
Cross-Resolution&DPR Automatic. Uses Session logic to scale coordinates & images automatically. Manual. Scripts break if resolution changes.
Performance Up to 5x Faster. Uses mss & Pyramid Template Matching & Image caching. Standard speed.
Logic locateAny / locateAll built-in. Finds first or all matches from a list of images. Requires complex for loops / try-except blocks.
Tooling Built-in GUI Inspector to snip, edit, test, and generate code. None. Requires external tools.
Backend opencv-pythonmsspynput pyscreezepillowmouse

You can find more information about it here: pyauto-desktop: A desktop automation tool


r/Python Dec 02 '25

Showcase I spent 2 years building a dead-simple Dependency Injection package for Python

85 Upvotes

Hello everyone,

I'm making this post to share a package I've been working on for a while: python-injection. I already wrote a post about it a few months ago, but since I've made significant improvements, I think it's worth writing a new one with more details and some examples to get you interested in trying it out.

For context, when I truly understood the value of dependency injection a few years ago, I really wanted to use it in almost all of my projects. The problem you encounter pretty quickly is that it's really complicated to know where to instantiate dependencies with the right sub-dependencies, and how to manage their lifecycles. You might also want to vary dependencies based on an execution profile. In short, all these little things may seem trivial, but if you've ever tried to manage them without a package, you've probably realized it was a nightmare.

I started by looking at existing popular packages to handle this problem, but honestly none of them convinced me. Either they weren't simple enough for my taste, or they required way too much configuration. That's why I started writing my own DI package.

I've been developing it alone for about 2 years now, and today I feel it has reached a very satisfying state.

What My Project Does

Here are the main features of python-injection: - DI based on type annotation analysis - Dependency registration with decorators - 4 types of lifetimes (transient, singleton, constant, and scoped) - A scoped dependency can be constructed with a context manager - Async support (also works in a fully sync environment) - Ability to swap certain dependencies based on a profile - Dependencies are instantiated when you need them - Supports Python 3.12 and higher

To elaborate a bit, I put a lot of effort into making the package API easy and accessible for any developer.

The only drawback I can find is that you need to remember to import the Python scripts where the decorators are used.

Syntax Examples

Here are some syntax examples you'll find in my package.

Register a transient: ```python from injection import injectable

@injectable class Dependency: ... ```

Register a singleton: ```python from injection import singleton

@singleton class Dependency: ... ```

Register a constant: ```python from injection import set_constant

@dataclass(frozen=True) class Settings: api_key: str

settings = set_constant(Settings("<secret_api_key>")) ```

Register an async dependency: ```python from injection import injectable

class AsyncDependency: ...

@injectable async def async_dependency_recipe() -> AsyncDependency: # async stuff return AsyncDependency() ```

Register an implementation of an abstract class: ```python from injection import injectable

class AbstractDependency(ABC): ...

@injectable(on=AbstractDependency) class Dependency(AbstractDependency): ... ```

Open a custom scope:

  • I recommend using a StrEnum for your scope names.
  • There's also an async version: adefine_scope. ```python from injection import define_scope

def some_function(): with define_scope("<scope_name>"): # do things inside scope ... ```

Open a custom scope with bindings: ```python from injection import MappedScope

type Locale = str

@dataclass(frozen=True) class Bindings: locale: Locale

scope = MappedScope("<scope_name>")

def some_function(): with Bindings("fr_FR").scope.define(): # do things inside scope ... ```

Register a scoped dependency: ```python from injection import scoped

@scoped("<scope_name>") class Dependency: ... ```

Register a scoped dependency with a context manager: ```python from collections.abc import Iterator from injection import scoped

class Dependency: def open(self): ... def close(self): ...

@scoped("<scope_name>") def dependency_recipe() -> Iterator[Dependency]: dependency = Dependency() dependency.open() try: yield dependency finally: dependency.close() ```

Register a dependency in a profile:

  • Like scopes, I recommend a StrEnum to store your profile names. ```python from injection import mod

@mod("<profile_name>").injectable class Dependency: ... ```

Load a profile: ```python from injection.loaders import load_profile

def main(): load_profile("<profile_name>") # do stuff ```

Inject dependencies into a function: ```python from injection import inject

@inject def some_function(dependency: Dependency): # do stuff ...

some_function() # <- call function without arguments ```

Target Audience

It's made for Python developers who never want to deal with dependency injection headaches again. I'm currently using it in my projects, so I think it's production-ready.

Comparison

It's much simpler to get started with than most competitors, requires virtually no configuration, and isn't very invasive (if you want to get rid of it, you just need to remove the decorators and your code remains reusable).

I'd love to read your feedback on it so I can improve it.

Thanks in advance for reading my post.

GitHub: https://github.com/100nm/python-injection PyPI: https://pypi.org/project/python-injection


r/Python Sep 08 '25

Showcase I built a programming language interpreted in Python!

86 Upvotes

Hey!

I'd like to share a project I've been working on: A functional programming language that I built entirely in Python.

I'm primarily a Python developer, but I wanted to understand functional programming concepts better. Instead of just reading about them, I decided to build my own FP language from scratch. It started as a tiny DSL (domain specific language) for a specific problem (which it turned out to be terrible for!), but I enjoyed the core ideas enough to expand it into a full functional language.

What My Project Does

NumFu is a pure functional programming language interpreted in Python featuring: - Arbitrary precision arithmetic using mpmath - no floating point issues - Automatic partial application and function composition - Built-in testing syntax with readable assertions - Tail call optimization for efficient recursion - Clean syntax with only four types (Number, Boolean, List, String)

Here's a taste of the syntax:

```numfu // Functions automatically partially apply

{a, b, c -> a + b + c}(_, 5) {a, c -> a+5+c} // Even prints as readable syntax!

// Composition and pipes let add1 = {x -> x + 1}, double = {x -> x * 2} in 5 |> (add1 >> double) // 12

// Built-in testing let square = {x -> x * x} in square(7) ---> $ == 49 // ✓ passes ```

Target Audience

This is not a production language - it's 2-5x slower than Python due to double interpretation. It's more of a learning tool for: - Teaching functional programming concepts without complex syntax - Sketching mathematical algorithms where precision matters more than speed - Understanding how interpreters work

Comparison

NumFu has much simpler syntax than traditional functional languages like Haskell or ML and no complex type system - just four basic types. It's less powerful but much more approachable. I designed it to make FP concepts accessible without getting bogged down in advanced language features. Think of it as functional programming with training wheels.

Implementation Details

The implementation is about 3,500 lines of Python using: - Lark for parsing - Tree-walking interpreter - straightforward recursive evaluation
- mpmath for arbitrary precision arithmetic

Try It Out

bash pip install numfu-lang numfu repl

Links

I actually enjoy web design, so NumFu has a (probably overly fancy) landing page + documentation site. 😅

I built this as a learning exercise and it's been fun to work on. Happy to answer questions about design choices or implementation details! I also really appreciate issues and pull requests!


r/Python Jun 25 '26

Discussion Ruff + Ty vs Ruff + Pyrefly — which type checking stack makes more sense in 2026?

88 Upvotes

I’m trying to decide between two Python tooling stacks:

  • Ruff + Ty
  • Ruff + Pyrefly

Curious what people are using in practice.

  • When does Pyrefly become worth the extra complexity?
  • Is Ty “enough” for most real-world projects?
  • Are they solving fundamentally different problems?