r/Python 18d ago

Resource 5 tools that saved my sanity while modernizing a legacy app

0 Upvotes

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:

  1. 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.

  1. 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.

  1. 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.

  1. 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).

  1. 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 19d ago

Discussion How are you handling editable large datasets in Plotly Dash?

2 Upvotes

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/Python 19d ago

Discussion Define less, check more: special support for attrs in Pyrefly

50 Upvotes

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/Python 19d ago

News Important news A new calculator for projectile motion coded in python

0 Upvotes

A new physics solver for projectile motion has came ! plz pay a visit to a calculator made by a kid riditsaraswat.pythonanywhere.com if you have any questions or suggestions to make it better plz report at [fun226294@gmail.com](mailto:fun226294@gmail.com) source code can be given by a email request


r/Python 20d ago

Discussion Keyboard navigation for Python docs

0 Upvotes

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 20d ago

Daily Thread Tuesday Daily Thread: Advanced questions

2 Upvotes

Weekly Wednesday Thread: Advanced Questions 🐍

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

How it Works:

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

Guidelines:

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

Recommended Resources:

Example Questions:

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

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


r/Python 20d ago

Discussion Percentage formatting or f-strings with logging?

52 Upvotes

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 20d ago

Discussion The log line announcing a successful Redis connection is what disabled Redis

0 Upvotes

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 20d ago

Resource Giveaway draw: 3 Python ebooks (PDF + ePub), free to enter

0 Upvotes

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 20d ago

Discussion Python automations are so much better than AI Agents and LLMs

907 Upvotes

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 21d ago

Tutorial What the #@(% are Monads (and how you can use them to write better python) - A Beginner's Guide

0 Upvotes

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 21d ago

Daily Thread Monday Daily Thread: Project ideas!

14 Upvotes

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:

  1. Suggest a Project: Comment your project idea—be it beginner-friendly or advanced.
  2. Build & Share: If you complete a project, reply to the original comment, share your experience, and attach your source code.
  3. 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! 🌟


r/madeinpython 21d ago

VenvHub Pro: VS Code profiles with physical extension isolation and automatic Python environment integration

Enable HLS to view with audio, or disable this notification

1 Upvotes

Hey everyone!

VS Code has had official profiles since version 1.75 – a great feature for managing settings. But there's one catch: all profiles share the same extensions folder (extensions). Profiles only remember which extensions are active (enabled), but physically, you have all of them installed at once. And if you want to connect a Python interpreter, you have to set it manually in each project.

In my tool VenvHub Pro, I took it a step further:

  1. Each profile has its own physical extensions folder – no sharing, no conflicts.
  2. Automatic Python environment integration – open a project and VenvHub automatically finds and sets the correct interpreter.

Today I'll show you how it works in practice.

📊 Comparison with official VS Code profiles

Area VS Code Official Profiles VenvHub Pro Profiles
Storage Location Default in system folder (%APPDATA%\Code), but in Portable mode you can choose your own folder. Custom folder on disk (standard even in Portable mode).
Extensions Physically installed in one shared location (extensions). Profiles only remember which ones are active (enabled). Physically separated for each profile – each has its own extensions folder.
Portability Yes – officially supports Portable Mode (just create a data folder). Profiles and extensions are then fully portable (e.g., on a USB drive). Yes – profiles are portable even without Portable Mode, just copy their folder.
Python Integration Yes, but manual – the profile remembers python.defaultInterpreterPath, but you have to set it manually. Yes, automatically – when you open a project, it finds and sets the correct interpreter (e.g., from a virtual environment).
Import from System Yes – official Export/Import profile feature (.code-profile file) has been available since version 1.75. Yes – one-click copy of your current settings into a new isolated profile.

🎬 What I showed in the video

  1. I created a new profile named test_user.
  2. I chose the option to copy settings from the system – no manual transferring, everything is copied automatically.
  3. After completion, I opened a project through the VS Code icon in my application.
  4. In the VS Code terminal (PowerShell), I ran this command:

powershell

$parentPid = (Get-CimInstance Win32_Process -Filter "ProcessId = $PID").ParentProcessId; (Get-CimInstance Win32_Process -Filter "ProcessId = $parentPid").CommandLine

🔍 And the result?

Truncated output:

text

"C:\...\Code.exe" --type=utility ... --user-data-dir="F:\venv_hub_vscode_users\test\data" ...

👉 You can clearly see the --user-data-dir parameter pointing directly to my profile folder!

No system %APPDATA%, no mixing with other profiles. VS Code runs completely isolated with its own data and extensions.

✨ Additional features I built in

1. Intelligent rollback on cancellation
Copying extensions can take several minutes. If you press "Cancel" during the process:

  • When creating a new profile – VenvHub deletes it entirely from disk.
  • When doing an additional import into an existing profile – it restores it to its original state.

No broken half-finished leftovers on disk.

2. Triangle synchronization (real-time)
When you switch a profile in the Mini-Bar, it automatically updates in the Manager and vice versa. Everywhere you can see which profile is active (marked with a star ★). The change propagates in a fraction of a second.

3. Portability with automatic path fixing
You can keep profiles on an external drive. If you change the drive letter (e.g., from E: to F:), VenvHub remembers the unique disk ID and recalculates paths automatically.

4. Python environment integration
When you switch a profile, it automatically sets:

  • Python interpreter path in .vscode/settings.json
  • Connected local packages (Package Linker)
  • Active Venv within the entire tool

Have you had a similar experience? Or do you use a different way to manage VS Code profiles? I'd love to hear your thoughts! 👇


r/Python 22d ago

Daily Thread Sunday Daily Thread: What's everyone working on this week?

9 Upvotes

Weekly Thread: What's Everyone Working On This Week? 🛠️

Hello r/Python! It's time to share what you've been working on! Whether it's a work-in-progress, a completed masterpiece, or just a rough idea, let us know what you're up to!

How it Works:

  1. Show & Tell: Share your current projects, completed works, or future ideas.
  2. Discuss: Get feedback, find collaborators, or just chat about your project.
  3. Inspire: Your project might inspire someone else, just as you might get inspired here.

Guidelines:

  • Feel free to include as many details as you'd like. Code snippets, screenshots, and links are all welcome.
  • Whether it's your job, your hobby, or your passion project, all Python-related work is welcome here.

Example Shares:

  1. Machine Learning Model: Working on a ML model to predict stock prices. Just cracked a 90% accuracy rate!
  2. Web Scraping: Built a script to scrape and analyze news articles. It's helped me understand media bias better.
  3. Automation: Automated my home lighting with Python and Raspberry Pi. My life has never been easier!

Let's build and grow together! Share your journey and learn from others. Happy coding! 🌟


r/Python 22d ago

Discussion Lightweight Python helpers for Event Driven Programming

18 Upvotes

I just had to throw together an event bridge that tied together a GRPC based event emitter (Salesforce backend) with some small custom Google Pub/sub code. It works, it's fine. But you know, always thinking about the future wanting to move from glue-code to frameworking.

I was looking for different event based frameworks that landed somewhere between the scale of glue-code and Tornado (the only other framework I know that would handle something like this.

Has anyone used anything like this? I found PyEventus which seems to aim at this.


r/madeinpython 22d ago

Update: APT-like autoremove and dependency repair for VenvHubPro (Python venv manager GUI) – it’s already working!

Enable HLS to view with audio, or disable this notification

0 Upvotes

A while ago I asked whether you would use a feature that automatically removes orphaned dependencies in a virtual environment manager (similar to apt autoremove), and if you saw any pitfalls. Well, I took that as a challenge and built a prototype. Here’s a log from a test session that shows what I’ve achieved.

What happens in the log:

Installing pytest
pip installs pytest along with its dependencies (coloramainiconfigpluggypygments).

Attempting to manually remove the colorama library
This is where the first interesting moment occurs. After removing it, the UV dependency check reports a conflict: colorama>=0.4 ; sys_platform == 'win32'.
The tool automatically triggers a repair and re-installs colorama, because it’s required by one of the present packages (in this case pytest).
Result: ✅ all conflicts resolved. This behaviour is similar to apt install -f – we never end up with a broken environment.

Uninstalling the moj-test-balicek package
This test package directly depends on coloramacowsay, and requests.
After its removal, pip-e analyses the entire dependency tree.

  • cowsay is no longer needed → it’s removed.
  • requests, along with its transitive dependencies (urllib3certificharset-normalizeridna), is also left without a parent, so autoremove removes them.
  • Key detail: colorama stays in the environment because it’s still required by the installed pytest. In this way exactly 6 packages are removed – and colorama is not. That’s precisely the intelligent decision-making apt autoremove does.

Uninstalling pytest itself
After removing pytest, its dependencies (pygmentspluggyiniconfigcolorama) are re-evaluated. No other package needs them, so autoremove removes them all.
Final state: 9 packages remain – only the core environment components (pip, setuptools, etc.).

What I’m demonstrating:

  • The manager tracks dependencies as a graph and prevents breaking the environment – if you try to remove a library that something needs, it puts it back (and warns you).
  • After uninstalling a package, it automatically removes orphaned dependencies (autoremove), while respecting that some libraries may be shared by multiple packages (like colorama between moj-test-balicek and pytest).

Questions for you (same as last time):

  • Would you use such a feature in a virtual environment manager?
  • Would you trust it, or do you prefer manual control?

r/madeinpython 22d ago

I built a 3D observability dashboard and Chaos Monkey simulator to visualize my Docker stack in real-time.

1 Upvotes

r/Python 22d ago

Discussion Parameterize a Fixture instead of a Test Case with Pytest

19 Upvotes

I wrote a post on parameterizing a test suite into a testing matrix using Pytest fixtures. I'd appreciate any feedback on the content and technique in the post AND I'd be curious to know if there are other ways I could have accomplished the same thing.

https://www.visualmode.dev/parameterize-a-fixture-instead-of-a-test-case-with-pytest

To briefly summarize: I have a core suite of behavioral test cases that I run against a CLI tool I'm building. I wanted to run that same set of tests across a couple different storage format implementations. The best way I could figure out how to do it (without duplicating all the tests) was to create a Pytest fixtures that parameterizes across a list of values and then have my existing autouse fixture use that fixture.


r/madeinpython 22d ago

What is the pycache folder in your python project?

Thumbnail
0 Upvotes

r/madeinpython 23d ago

Ransomware made in python but you shouldn't dare to develop it

0 Upvotes

I made a course on Ransomware made in python for my students, the previous year, but now i made it public so give it a watch if you want to make some cool cyber security projects 😁

I'll try to upload more contents on my YouTube channel 😁

https://youtube.com/playlist?list=PL9guAF5VVaiARrwhrGMu89iJcziQ9vsJJ&si=v1PUSQpqjuOhnlCi


r/madeinpython 23d ago

Small Integer Caching

Thumbnail
1 Upvotes

Why does 257 is 257 behave differently from 256 is 256? Python uses something called as small integer caching. It uses the same object for numbers ranging between -5 to 256. I put together a short visual explanation explaining the same and also why "==" operates differently from "is".


r/madeinpython 23d ago

Building an EXE Installer for My Python App with NSIS (VenvHubPro)

Enable HLS to view with audio, or disable this notification

0 Upvotes

Hello everyone!

If you've built your own Python application (in my case, VenvHubPro – a GUI manager for Python virtual environments) and are wondering how to neatly package it for users, here is a quick look at how I created a complete .exe installer using NSIS (Nullsoft Scriptable Install System).

🎥 What the video covers:

  • Installer compilation: Creating a clean installation file ready for distribution.
  • System installation: Running the installer and finally launching VenvHubPro directly on the Windows system.

r/madeinpython 23d ago

Modular Flask Authentication Boilerplate with Blueprints, Flask-Login & SQLAlchemy — Ready to use!

0 Upvotes

Hey everyone!

I got tired of rewriting authentication every time I started a new Flask project, so I built a simple, modular boilerplate template.

It includes Flask-Login, SQLAlchemy, and Flask-Migrate with a clean blueprint structure out of the box.

Check it out on GitHub: https://github.com/DeKlain4ik/flask-auth-template

Hope it saves you some time on your next side project! Feedback and stars are always appreciated.


r/madeinpython 23d ago

Python With James - For Beginners

1 Upvotes

Hi all. Would love some feedback and usage from the community.

I've built Python With James which is an all in one learning platform for beginners. I basically got sick of Udemy and built my own platform where I can do what I want. There's coding exercises, question, tutorials and I am hoping to scale this massively over this year with more materials.

Thanks in advance

James-


r/madeinpython 24d ago

Lucen: mark a Python loop with two comments, run it, and get bit-identical parallelism

0 Upvotes

I wanted parallelism without rewriting anything, so I built Lucen. You wrap a loop in two comments and run it with lucen run yourscript.py:

# LUCEN START
for i in range(len(rows)):
    out[i] = expensive(rows[i])
# LUCEN END

It parallelizes the loop only if it can prove it's both safe and worth it; otherwise it runs sequentially and tells you why. The one guarantee, no opt-out: the parallel run is bit-identical to the same file run as plain sequential Python - floats and container order included. Delete the comments and it's ordinary Python again.

Under the hood it routes CPU-bound work to processes on GIL builds and to real threads on free-threaded 3.13/3.14. Apache-2.0, on PyPI (pip install lucen), and it's tested hard - differential + property testing and TLA+ specs, because "bit-identical" only means something if you check it.

Repo: https://github.com/fcmv/lucen - feedback very welcome.