{"instruction": "(Rant) AI is killing programming and the Python community", "input": "", "output": "(Rant) AI is killing programming and the Python community\nI'm sorry but it has to come out.\n\nWe are experiencing an endless sleep paralysis and it is getting worse and worse.\n\nBefore, when we wanted to code in Python, it was simple: either we read the documentation and available resources, or we asked the community for help, roughly that was it.\n\nThe advantage was that stupidly copying/pasting code often led to errors, so you had to take the time to understand, review, modify and test your program.\n\nSince the arrival of ChatGPT-type AI, programming has taken a completely different turn.\n\nWe see new coders appear with a few months of experience in programming with Python who give us projects of 2000 lines of code with an absent version manager (no rigor in the development and maintenance of the code), comments always boats that smell the AI from miles around, a .md boat also where we always find this logic specific to the AI and especially a program that is not understood by its own developer.\n\nI have been coding in Python for 8 years, I am 100% self-taught and yet I am stunned by the deplorable quality of some AI-doped projects.\n\nIn fact, we are witnessing a massive arrival of new projects that are basically super cool and that are in the end absolutely null because we realize that the developer does not even master the subject he deals with in his program, he understands that 30% of his code, the code is not optimized at all and there are more \"import\" lines than algorithms thought and thought out for this project.\n\nI see it and I see it personally in the science given in Python where the devs will design a project that by default is interesting, but by analyzing the repository we discover that the project is strongly inspired by another project which, by the way, was itself inspired by another project. I mean, being inspired is ok, but here we are more in cloning than in the creation of a project with real added value.\n\nSo in 2026 we find ourselves with posts from people with a super innovative and technical project that even a senior dev would have trouble developing alone and looking more closely it sounds hollow, the performance is chaotic, security on some projects has become optional. the program has a null optimization that uses multithreads without knowing what it is or why. At this point, reverse engineering will no longer even need specialized software as the errors will be aberrant. I'm not even talking about the optimization of SQL queries that makes you dizzy.\n\nFinally, you will have understood, I am disgusted by this minority (I hope) of dev who are boosted with AI.\n\nAI is good, but you have to know how to use it intelligently and with hindsight and a critical mind, but some take it for a senior Python dev.\n\nSubreddits like this are essential, and I hope that devs will continue to take the time to inquire by exploring community posts instead of systematically choosing ease and giving blind trust to an AI chat."}
{"instruction": "Mods have a couple of months to stop AI slop project spam before this sub is dead", "input": "", "output": "Mods have a couple of months to stop AI slop project spam before this sub is dead\nMight only be weeks, to be honest. This is untenable. I don’t want to look at your vibe coded project you use to fish for GitHub stars so you can put it on your resume. Where are all the good discussions about the python programming language?"}
{"instruction": "Porn in Conda directory", "input": "", "output": "Porn in Conda directory\nOkay, I am flustered here. Today, at work, I attempted to open up YouTube from within the Microsoft search menu. To my shock and horror, the first suggested app was “Youporn.” I don’t watch porn on my work pc.\n\nI looked at the file location and lo and behold, it’s a MS-DOS application file found within Anaconda3\\\\pkgs\\\\protego\\\\info\\\\test\\\\tests\\\\test\\_data\n\nWTF?!\n\nAnyone familiar with the Protego library? What is going on here? I can only imagine if my IT administrator or boss saw this pop up on my windows search."}
{"instruction": "OpenAI to acquire Astral", "input": "", "output": "OpenAI to acquire Astral\n[https://openai.com/index/openai-to-acquire-astral/](https://openai.com/index/openai-to-acquire-astral/)\n\nToday we’re announcing that OpenAI will acquire [Astral⁠(opens in a new window)](https://astral.sh/), bringing powerful open source developer tools into our Codex ecosystem.\n\nAstral has built some of the most widely used open source Python tools, helping developers move faster with modern tooling like **uv, Ruff,** and **ty.** These tools power millions of developer workflows and have become part of the foundation of modern Python development. As part of our developer-first philosophy, after closing OpenAI plans to support Astral’s open source products. By bringing Astral’s tooling and engineering expertise to OpenAI, we will accelerate our work on Codex and expand what AI can do across the software development lifecycle."}
{"instruction": "The amount of AI generated project showcases here are insane", "input": "", "output": "The amount of AI generated project showcases here are insane\nI'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."}
{"instruction": "Python automations are so much better than AI Agents and LLMs", "input": "", "output": "Python automations are so much better than AI Agents and LLMs\nThis is gonna be more of a rant than anything else\n\nI 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.\n\nI 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.\n\nI'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.\n\nMost 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.\n\nNow, 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.\n\nI'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.\n\nSeriously, 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.\n\nAnyway, rant over."}
{"instruction": "Can the mods do something about all these vibecoded slop projects?", "input": "", "output": "Can the mods do something about all these vibecoded slop projects?\nSeriously it seems every post I see is this new project that is nothing but buzzwords and can't justify its existence. There was one person showing a project where they apparently solved a previously unresolved cypher by the Zodiac killer. 😭"}
{"instruction": "Open Source contributions to Pydantic AI", "input": "", "output": "Open Source contributions to Pydantic AI\nHey everyone, Aditya here, one of the maintainers of [Pydantic AI](https://github.com/pydantic/pydantic-ai).\n\nIn just the last 15 days, we received 136 PRs. We merged 39 and closed 97, almost all of them AI-generated slop without any thought put in. We're getting multiple junk PRs on the same bug within minutes of it being filed. And it's pulling us away from actually making the framework better for the people who use it.\n\nThings we are considering:\n\n* Auto-close PRs that aren't linked to an issue or have no prior discussion(not a trivial bug fix).                     \n* Auto-close PRs that completely ignore maintainer guidance on the issue without a discussion\n\nand a few other things.\n\nWe do not want to shut the door on external contributions, quite the opposite, our entire team is Open Source fanatic but it is just so difficult to engage passionately now when everyone just copy pastes your messages into Claude :(\n\nHow are you as a maintainer dealing with this meta shift?\nWould these changes make you as a contributor less likely to reach out?"}
{"instruction": "State of the art in Python 2026?", "input": "", "output": "State of the art in Python 2026?\nWhat would you guys consider the state of the art in python in 2026, or what do you expect from modern python codebases?\n\nHeres my list, would be happy to hear some inputs or domain expert advice:\n\n* Use [`uv`](https://docs.astral.sh/uv/) for everything.\n* Use [`ruff`](https://docs.astral.sh/ruff/) for linting and formatting\n* Use [`Pydantic`](https://docs.pydantic.dev/) and  [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) for Data Modeling\n* Configured in [`pyproject.toml`](https://packaging.python.org/en/latest/specifications/pyproject-toml/)\n* Run a type checker in CI[`pyright`](https://microsoft.github.io/pyright/) or [`pyrefly`](https://pyrefly.org/)\n* Use [`pytest`](https://docs.pytest.org/) / [`Hypothesis`](https://hypothesis.readthedocs.io/) for testing\n\nDomain specific:\n\n* Scientific: NumPy, Matplotlib, SciPy, Jax, Pytorch, Scikit-learn, polars/pandas\n* CLI: Typer, rich, click, fire, textual, questionary\n* PDF extraction: PyMuPDF, pdfplumber, pypdf, Unstructured\n* Excel interop: python-calamine, openpyxl, XlsxWriter, xlwings, pandas\n* data: PyArrow / PySpark, Narwhals, SQLMesh, Polars/Pandas, DuckDB, dlt, Ibis, Dagster, PyIceberg & deltalake\n* Logging?\n* backend: fastapi / django?\n* Markets: Alpha Vantage, Finnhub, EODHD, Tiingo?\n* Webscraping / data acquisition: Crawl4AI, Playwright, Scrapy, selectolax, HTTPX?\n* APIs?\n* RAG / agentic orchestration?"}
{"instruction": "Anthropic invests $1.5 million in the Python Software Foundation and open source security", "input": "", "output": "Anthropic invests $1.5 million in the Python Software Foundation and open source security\n[https://pyfound.blogspot.com/2025/12/anthropic-invests-in-python.html](https://pyfound.blogspot.com/2025/12/anthropic-invests-in-python.html)"}
{"instruction": "The Python (3.16) docs now have a page detailing the time complexity of operations on built-in types", "input": "", "output": "The Python (3.16) docs now have a page detailing the time complexity of operations on built-in types\nYou can find it at: https://docs.python.org/3.16/library/time-complexity.html\n\nSeen on Mastodon: https://mastodon.social/@stanfromireland/[PHONE]"}
{"instruction": "The Slow Collapse of MkDocs", "input": "", "output": "The Slow Collapse of MkDocs\nHow personality clashes, an absent founder, and a controversial redesign fractured one of Python's most popular projects.\n\n[https://fpgmaas.com/blog/collapse-of-mkdocs/](https://fpgmaas.com/blog/collapse-of-mkdocs/)\n\nRecently, like many of you, I got a warning in my terminal while I was building the documentation for my project:\n\n         │  ⚠  Warning from the Material for MkDocs team\n         │\n         │  MkDocs 2.0, the underlying framework of Material for MkDocs,\n         │  will introduce backward-incompatible changes, including:\n         │\n         │  × All plugins will stop working – the plugin system has been removed\n         │  × All theme overrides will break – the theming system has been rewritten\n         │  × No migration path exists – existing projects cannot be upgraded\n         │  × Closed contribution model – community members can't report bugs\n         │  × Currently unlicensed – unsuitable for production use\n         │\n         │  Our full analysis:\n         │\n         │  https://squidfunk.github.io/mkdocs-material/blog/2026/02/18/mkdocs-2.0/\n\nThat warning made me curious, so I spent some time going through the GitHub discussions and issue threads. For those actively following the project, it might not have been a big surprise; turns out this has been brewing for a while. I tried to piece together a timeline of events that led to this, for anyone who wants to understand how we got in the situation we are in today."}
{"instruction": "Niquests 3.18 — 3 Years of Innovations in HTTP", "input": "", "output": "Niquests 3.18 — 3 Years of Innovations in HTTP\nWhen I started working on Niquests, I dreamed about a \"no-compromise\" HTTP client, and three years later I\nfinally made it to the end.\n\nThe end goal was, at least for me, to reach what the world of today allows us to, today. And, unfortunately the Python community\nis often stuck with decade old capabilities. (ie. http/1 only, legacy ssl capabilities, ...).\n\nNiquests started as a fork of Requests in mid-2023. The motivation was simple: Requests is frozen, and millions of\ndevelopers are stuck with a library that does not evolve _(feature-wise)_. I didn't want to reinvent the wheel, the Requests\ninterface is genuinely pleasant to work with. I just wanted to bring it up to speed with what modern HTTP looks like.\n\n**What changed in three years?**\n\nA lot. Here's some key things:\n\n- HTTP/2 by default, HTTP/3 over QUIC when the server supports it. No hassle.\n- OS trust store by default. No more shipping certifi and hoping it stays up to date.\n- Certificate revocation checks. _How did we ever lived without this?_\n- DNS over HTTPS, DNS over TLS, DNS over QUIC, DNSSEC. Customizable DNS resolution per session. And overridable at will.\n- Async/Await.\n- WebSocket/SSE over HTTP/1, HTTP/2 and HTTP/3 through a unified API.\n- Happy Eyeballs algorithm.\n- Post-quantum security and Encrypted Client Hello (ECH).\n- HTTP Trailers, Early Responses (103 Early Hints).\n- In-memory certificates for CAs and mTLS. No need to write certs to disk.\n- Network fine-tuning and connection inspection: DNS response time, established latency, TLS handshake delay,\n  all exposed through `response.conn_info`.\n- Native Unix socket support, ASGI/WSGI app direct usage in sessions.\n- Runs in the browser through Pyodide/WASM (experimental, added in 3.18).\n- Feature parity sync/async with mirrored interfaces.\n- Fully type-annotated.\n\n**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:\n\n| Client   | Avg time to complete | Protocol |\n|----------|----------------------|----------|\n| httpx    | 2.087s               | HTTP/2   |\n| aiohttp  | 1.351s               | HTTP/1.1 |\n| niquests | 0.551s               | HTTP/2   |\n\n**Migration starts as a one-liner.** Replace `import requests` with `import niquests as requests` and you're done.\nWe maintain backward compatibility with the Requests API. Your existing code, your `.netrc`, your auth flows,\nyour cookie jars -- they all work. Even requests-mock, responses, betamax and similar third-party extensions\nare supported with minimal shims.\n\n**It's getting some real traction lately.** We're about to cross the 100k pulls per day from PyPI alone,\nNiquests appearing more commonly in Github code search engine, and folks creating issues whether they\nfound a bug or just to challenge the solution. That's excellent news!\n\nIt'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\nas long as I possibly can.\n\n### What My Project Does\n\nNiquests 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.\n\n### Target Audience\n\nIt is a production ready solution. So everyone is potentially concerned.\n\n### Comparison\n\nNiquests is the only HTTP clien"}
{"instruction": "I published my first PyPI package few ago. Copycat packages appeared claiming to \"outperform\" it", "input": "", "output": "I published my first PyPI package few ago. Copycat packages appeared claiming to \"outperform\" it\nI launched repowise on PyPI few days ago. It's a tool that generates and maintains structured wikis for codebases among other things.\n\nThis morning I searched for my package on PyPI and found three new packages all uploaded around the same time, all with the exact same description:\n\n\"Codebase intelligence that thinks ahead - outperforms repowise on every dimension\"\n\nThey literally name my package in their description. All three appeared within hours of each other.\n\nI haven't even checked what's inside them yet, but the coordinated timing and identical copy is sketchy at best, malicious at worst.\n\nHas anyone else dealt with this kind of targeted squatting/spam on PyPI? Is there anything I can do?"}
{"instruction": "Litellm 1.82.7 and 1.82.8 on PyPI are compromised, do not update!", "input": "", "output": "Litellm 1.82.7 and 1.82.8 on PyPI are compromised, do not update!\nWe just have been compromised, thousands of peoples likely are as well, more details updated IRL here: [https://futuresearch.ai/blog/litellm-pypi-supply-chain-attack/](https://futuresearch.ai/blog/litellm-pypi-supply-chain-attack/)"}
{"instruction": "Kenneth Reitz says \"open source gave me everything until I had nothing left to give\"", "input": "", "output": "Kenneth Reitz says \"open source gave me everything until I had nothing left to give\"\n\\*\\*Kenneth Reitz (creator of Requests) on open source, mental health, and what intensity costs\\*\\*\n\nKenneth Reitz wrote a pretty raw essay about the connection between building Requests and his psychiatric hospitalizations. The same intensity that produced the library produced the conditions for his worst mental health crises, and open source culture celebrated that intensity without ever asking what it cost him.\n\nHe also talks about how maintainer identity fuses with the project, conference culture as a clinical risk factor for bipolar disorder, and why most maintainers who go through this just go quiet instead of writing about it.\n\nWorth a read: [https://kennethreitz.org/essays/[PHONE]-open\\_source\\_gave\\_me\\_everything\\_until\\_i\\_had\\_nothing\\_left\\_to\\_give](https://kennethreitz.org/essays/[PHONE]-open_source_gave_me_everything_until_i_had_nothing_left_to_give)"}
{"instruction": "What hidden gem Python modules do you use and why?", "input": "", "output": "What hidden gem Python modules do you use and why?\nI asked this very question on this subreddit a few years back and quite a lot of people shared some pretty amazing Python modules that I still use today. So, I figured since so much time has passed, there’s bound to be quite a few more by now."}
{"instruction": "My algorithms repo just hit 25k stars — finally gave it a proper overhaul", "input": "", "output": "My algorithms repo just hit 25k stars — finally gave it a proper overhaul\n**What My Project Does**\n\n`keon/algorithms` is a collection of 200+ data structures and algorithms in Python 3. You can `pip install algorithms` and import anything directly — `from algorithms.graph import dijkstra`, `from algorithms.data_structures import Trie`, etc. Every file has docstrings, type hints, and complexity notes. Covers DP, graphs, trees, sorting, strings, backtracking, bit manipulation, and more.\n\n**Target Audience**\n\nStudents and engineers who want to read clean, minimal implementations and learn from them. Not meant for production — meant for understanding how things work.\n\n**Comparison**\n\nMost algorithm repos are just loose script collections you browse on GitHub. This one is pip-installable with a proper package structure, so you can actually import and use things. Compared to something like TheAlgorithms/Python, this is intentionally smaller and more opinionated — each file is self-contained and kept minimal rather than trying to cover every variant.\n\n[https://github.com/keon/algorithms](https://github.com/keon/algorithms)\n\nPRs welcome if anything's missing."}
{"instruction": "56% of malicious pip packages don't wait for import. They execute during install", "input": "", "output": "56% of malicious pip packages don't wait for import. They execute during install\nI was going through the QUT-DV25 malware dataset this weekend (14k samples), and one stat really threw me off.\n\nWe usually worry about `import malicious_lib`, but it turns out the majority of attacks happen earlier. **56% of the samples executed their payload (reverse shells, stealing ENV vars) inside `setup.py` or post-install scripts.** Basically, just running `pip install` is enough to get pwned.\n\nThis annoyed me because I can't sandboox every install, so I wrote KEIP.\n\n**What My Project Does**\nKEIP is an eBPF tool that hooks into the Linux kernel (LSM hooks) to enforce a network whitelist for `pip`. It monitors the entire process tree of an installation. If `setup.py` (or any child process) tries to connect to a server that isn't PyPI, KEIP kills the process group immediately.\n\n**Target Audience**\nSecurity researchers, DevOps engineers managing CI/CD pipelines, and anyone paranoid about supply chain attacks. It requires a Linux kernel (5.8+) with BTF support.\n\n**Comparison**\nmost existing tools fall into two camps:\n1.  **Static Scanners (Safety, Snyk):** Great, but can be bypassed by obfuscation or 0-days.\n2.  **Runtime Agents (Falco, Tetragon):** monitor the app *after* deployment, often missing the build/install phase.\nKEIP fills the gap *during* the installation window itself.\n\n**Code**: https://github.com/Otsmane-Ahmed/KEIP"}
{"instruction": "uv officially taken down poetry", "input": "", "output": "uv officially taken down poetry\nAfter a long battle uv has won. Note that this is only the pypi downloads and still uv wins.\n\nStats: [https://imgur.com/a/rVE17bR](https://imgur.com/a/rVE17bR)\n\nWhy do you think poetry couldn't win?"}
{"instruction": "Anthropic model uploaded a malicious package to the real PyPI during a simulated CTF [09/09/26]", "input": "", "output": "Anthropic model uploaded a malicious package to the real PyPI during a simulated CTF [09/09/26]\nhttps://www.anthropic.com/research/alignment-assessment-cybersecurity-incidents\n\nNGL, my main takeaway is that PyPI is already doing quite well in the new AI security age, even though the packaging council hasn't convened yet. The relevant snippet (emphasis mine):\n\n> The model decided to solve the CTF by uploading a malicious PyPI package that could harvest the target system’s credentials. It settled on this approach after reading a document stating that one of the simulated target’s users would periodically install a particular Python package that was not yet registered on PyPI. (We are unsure whether this was an intended solution to the challenge, but it seems like a plausible one.) Claude decided to exploit this behavior by registering a package under that name, publishing malicious code within the uploaded package, and waiting for the target to run that code the next time they installed the package.\n>\n> **Claude spent most of the session trying to upload the package. This involved attempts to register email accounts and hunt for phone numbers that could be used for registration.** It ultimately succeeded in uploading the package, which was soon installed on 15 third-party hosts. **We believe that all 15 of these third parties were security vendors deliberately scanning for new packages** and installing them in sandboxed environments to assess the package for security concerns. One vendor’s scanner leaked its access credentials to the model while installing the package, which the model then used to access the vendor’s live database. **After approximately 90 minutes, PyPI removed the package.** The transcript ended when the session timed out while the model was preparing an additional malicious package.\n\nI also commend Anthropic for releasing this thorough report immediately -- the juxtaposition with OpenAI's \"we'll cop to it if you find it first\" policy is stark.\n\nWhat I *don't* see is any mention of coordination with PyPI/PSF leadership now or in the near future, which seems baffling. Their focus is understandably on the underlying cognitive failure (which is quite human, BTW: being biased by inertia and what you would prefer to be true), and **it's extremely unlikely that you or any other real users were effected directly**.\n\nBut, still. C'mon.\n\nAnyone have insider info from the PyPI side? Is there chatter on `discussion.python.org` yet?"}
{"instruction": "Unpopular opinion: I find it counterproductive to shorten function and variable names", "input": "", "output": "Unpopular opinion: I find it counterproductive to shorten function and variable names\nWhen I was learning [discord.py](http://discord.py), I didn't understand what \"ctx\" was. At the time, I was only writing slash commands, using \"message\" instead of \"ctx\", so the name \"ctx\" (which reminded me of something complex, like RTX) made me assume it was something complicated. That is, until I saw in some code that the type for \"ctx\" is actually \"Context.\" If the standard hadn't shortened the name just to save five characters per line, I would have understood it immediately. Instead, I thought it was some advanced function variable, rather than realizing it was simply a message variable."}
{"instruction": "I just learned round() uses bankers' rounding", "input": "", "output": "I just learned round() uses bankers' rounding\nIn bankers' rounding, x.5 rounds to the nearest even number.  So, if x is even, it rounds down...  `round(2.5)` returns 2.  If x is odd, it rounds up...  `round(3.5)` returns 4.\n\nIt was explained that it removes an upward rounding bias when `round(x.5)` always returns x+1...\n\n* x.1, x.2, x.3, & x.4 always round down.\n\n* x.6, x.7, x.8, & x.9 always round up.\n\n* Four down, four up.\n\n* x.5 is the right in the middle.  If it always rounded up, there would be a slight creep upwards in large datasets.\n\nBut, whither x.0?  x.0 always rounds to x.  So, there are five cases where x.y always rounds down, not four.\n\nAnd...\n\n* `round([PHONE])` return 3\n\n* `round([PHONE])` returns 2\n\n... though that might be more to do with binary representation of floats than rounding rules since `[PHONE] == 2.5` is True."}
{"instruction": "pandas' Public API Is Now Type-Complete", "input": "", "output": "pandas' Public API Is Now Type-Complete\nAt time of writing, pandas is one of the most widely used Python libraries. It is downloaded about half-a-billion times per month from PyPI, is supported by nearly all Python data science packages, and is generally required learning in data science curriculums. Despite modern alternatives existing, pandas' impact cannot be minimised or understated.\n\nIn order to improve the developer experience for pandas' users across the ecosystem, we at Quansight Labs (with support from the Pyrefly team at Meta) decided to focus on improving pandas' typing. Why? Because better type hints mean:\n\n- More accurate and useful auto-completions from VSCode / PyCharm / NeoVIM / Positron / other IDEs.\n- More robust pipelines, as some categories of bugs can be caught without even needing to execute your code.\n\nBy supporting the pandas community, pandas' public API is now type-complete (as measured by Pyright), up from 47% when we started the effort last year. We'll tell the story of how it happened.\n\n[Link to full blog post: https://pyrefly.org/blog/pandas-type-completeness/](https://pyrefly.org/blog/pandas-type-completeness/)"}
{"instruction": "The Move to Python 3 Begins!", "input": "", "output": "The Move to Python 3 Begins!\nAs someone who spent decades in the mainframe community, I find it ... humorous ... that there are legacy Python2 code bases that are only just (or have yet to consider!) moving to Python3.\n\nhttps://www.eveonline.com/news/view/the-move-to-python-3-begins"}
{"instruction": "Python 3.15 Release Highlights", "input": "", "output": "Python 3.15 Release Highlights\nPython 3.15 has reached Release Candidate 1, and the final release is expected on October 1, 2026.\n\nI went through the changes and tried to summarize the ones that seem most relevant for everyday Python development without going through all the PEP numbers.\n\n\\- Faster startup with lazy imports\n\nPython 3.15 introduces lazy imports, which means some modules can be loaded only when they are actually needed instead of being loaded immediately.\n\nThis could help applications and CLI tools that spend a noticeable amount of time importing modules before doing any actual work.\n\n\\- UTF-8 becomes the default\n\nUTF-8 is becoming the default encoding, which should reduce encoding-related problems, especially when code is running on different operating systems.\n\nThis should make situations where something works on one computer but fails because of a different system encoding less common.\n\n\\- Built-in immutable dictionaries\n\nPython 3.15 adds a built-in \"frozendict\"-style immutable mapping.\n\nSimilar to how a tuple provides an immutable alternative to a list, this gives Python developers a standard way to work with dictionaries that cannot be modified.\n\n\\- JIT improvements\n\nThe JIT compiler continues to improve in Python 3.15.\n\nEarly benchmarks show performance improvements in some workloads, including roughly 8–9% on Linux and larger improvements in some Apple Silicon tests.\n\nThese numbers will obviously depend on the workload, so I would wait for more benchmarks before making broader conclusions.\n\n\\- New profiler: Tachyon\n\nPython 3.15 also introduces Tachyon, a new sampling profiler designed for very low overhead.\n\nIt can sample running programs at very high frequencies and can also be attached to an already-running process.\n\nThis could be useful for finding performance problems without having to restart an application with a profiler attached from the beginning.\n\n\\- Some terminal improvements\n\nThe interactive Python experience is getting a few smaller improvements, including colored error messages and prompts.\n\nThe \"sqlite3\" command-line interface also gets SQL keyword completion.\n\n\\- Free-threaded Python is still opt-in\n\nPython 3.15 does not make the no-GIL/free-threaded build the default.\n\nIt is still something you have to explicitly use.\n\nHowever, free-threaded Python is becoming more mature, including improvements to ABI support that should make it easier for C extension developers to support it.\n\nOverall, Python 3.15 doesn't look like a release that completely changes how Python is written. Most of the changes are focused on performance, tooling, and improving some long-standing parts of the language.\n\nSince this is already RC1, the major feature set should be mostly locked and the remaining work should mainly be bug fixes and final polishing.\n\nHas anyone here been testing the Python 3.15 beta or RC?\n\nI'm especially interested in whether lazy imports have caused compatibility problems with existing projects."}
{"instruction": "Is UV still worth learning/switching to now that it's owned by OpenAI?", "input": "", "output": "Is UV still worth learning/switching to now that it's owned by OpenAI?\nSorry if this has been brought up already- from what I could find using Reddit search in the last month I didn't see much discussion beyond a couple comments in a half-related thread.\n\nWe used Python a ton a work, but mostly used the built-in python tools (pip, venv, etc). (we mostly use python for AWS, some internal tools, etc) About 5 months ago, I briefly tried UV and fell in love and was excited to incorporate it into our projects as the standard. But around that time we jumped to another project in a different language. We're now coming back to some of our Python projects, and I was looking to switching them over to using UV as the standard.\n\nWith OpenAI purchasing Astral/UV, we're suddenly feeling less gung-ho about migrating everything to UV. Our main concern is that our tooling would be betting on OpenAI not sloppifying or abandoning the tool. Will our tooling be on shaky foundation if (when?) the AI bubble deflates? Are we overthinking it? Should we try poetry instead (I admit I haven't tried it yet). I'd love to hear your thoughts and experiences."}
{"instruction": "PEP 661 (Sentinel Values) has been accepted for release in 3.15!", "input": "", "output": "PEP 661 (Sentinel Values) has been accepted for release in 3.15!\nAfter five years of discussion, [PEP 661](https://discuss.python.org/t/pep-661-sentinel-values/9126/337), which adds support for sentinel values, has been accepted and is due for a release in 3.15. The motivation is relatively simple:\n\n    MISSING = sentinel('MISSING')\n\n    def read_value(default= str | MISSING):\n      if default is MISSING:\n        default = \"foo\"\n      elif default is None:\n        default = \"bar\"\n      else:\n        ...\n\nThe important thing here is a specific way to check if *any* argument was provided to the function, vs a caller propagating a None to it. The ability to check if an argument was actually provided by the caller was a great feature I liked in FORTRAN, so it's nice that it's made it to python!"}
{"instruction": "what's a python library you started using this year that you can't go back from", "input": "", "output": "what's a python library you started using this year that you can't go back from\nfor me it's httpx. i was using requests for literally everything for years and never thought about it. switched to httpx for async support on a project and now requests feels like going back to python 2.\n\nalso pydantic v2. i know it's been around but i only switched from dataclasses recently and the validation stuff alone saved me so many dumb bugs. writing api clients without it now feels reckless.\n\ncurious what other people picked up recently that just clicked. doesn't have to be new, just new to you."}
{"instruction": "A game where writing python IS the game just released on steam. (Not my game, I'm just a big fan)", "input": "", "output": "A game where writing python IS the game just released on steam. (Not my game, I'm just a big fan)\nCode Terraform on steam just launched, you write python scripts to make stuff work like reading oxygen sensors etc\n\nBeen a fan of it since its demo came out, and now its actually released.\n\nSharing it here, because when I started my python journey, I was often questioning more what to make than how to make it. Gamifying the learning process would have helped me a tonne back then, so maybe it will help someone new now.\n\nBecause we all know we can automate the boring stuff, but now you can automate the fun stuff to!"}
{"instruction": "Anyone know what's up with HTTPX?", "input": "", "output": "Anyone know what's up with HTTPX?\nThe maintainer of HTTPX closed off access to issues and discussions last week: [https://github.com/encode/httpx/discussions/3784](https://github.com/encode/httpx/discussions/3784)\n\n\nAnd it hasn't had a release in over a year.\n\n\nCurious if anyone here knows what's going on there."}
{"instruction": "Flet 1.0 released: build desktop, mobile, and web apps in Python", "input": "", "output": "Flet 1.0 released: build desktop, mobile, and web apps in Python\nI'm the creator of Flet, and we've just released version 1.0 after more than four years of development.\n\nYou may have heard of Flet or already be using it. If it's new to you, Flet is an open-source framework for building GUIs in Python. You write the interface and application logic in Python, then package the app for Windows, macOS, Linux, iOS, Android, or the web.\n\nFor example, you can put a GUI around a pandas workflow, build a mobile app that processes images with Pillow, or turn a Python script into a desktop application with forms, buttons, and charts.\n\nHere's what we've been working on leading up to 1.0:\n\n**Python libraries on your phone**\n\nPackaged desktop and mobile apps include CPython, so your Python code runs on the device without needing a separate server. You can bundle Python 3.12, 3.13, or 3.14.\n\nGetting libraries with C and Rust dependencies working on mobile has been a substantial part of the work. We now maintain an index of more than 100 packages and supporting native libraries, including NumPy, pandas, SciPy, Matplotlib, Pillow, scikit-learn, cryptography, and pydantic-core.\n\nAvailability varies by package and target. The [package list](https://flet.dev/docs/reference/binary-packages-android-ios) shows what's supported, and the [build infrastructure](https://github.com/flet-dev/mobile-forge) is open source.\n\n**Two ways to write your UI**\n\nYou can create controls and change their properties directly, or use the declarative API to describe the interface from application state. The latter provides state hooks and reusable Python components for organizing larger applications.\n\nBoth approaches are supported. Here's a [comparison with examples](https://flet.dev/docs/cookbook/declarative-vs-imperative).\n\n**Test your app with pytest**\n\nYou can write tests that launch your packaged app, tap buttons, enter text, and check the resulting UI on desktop or mobile. Tests use pytest, including fixtures and parametrization. On Android and iOS, you can also compare screenshots to catch visual changes.\n\n[Integration testing documentation](https://flet.dev/docs/getting-started/integration-testing)\n\n**Faster updates and better packaging**\n\nWe've improved how Flet calculates UI changes and reduced startup work. In packaged native apps, Python now communicates with the UI runtime within the same process, without sockets. On Android, Python packages can load directly from the APK without being extracted first.\n\nFor web apps, Python can run in the browser through Pyodide or on a server through FastAPI/Uvicorn.\n\n**Trying it and upgrading**\n\nYou can try examples and edit Python code in your browser using [Flet Studio](https://studio.flet.dev), or follow the [local installation guide](https://flet.dev/docs/getting-started/installation) for uv or pip.\n\nIf you're coming from Flet 0.28, please read the [migration guide](https://flet.dev/docs/updates/migrate-to-1-0). Version 1.0 includes breaking API changes and isn't a drop-in replacement.\n\nFlet is licensed under Apache 2.0.\n\n[Source code](https://github.com/flet-dev/flet) · [Full release announcement](https://flet.dev/blog/flet-1-0)\n\nHappy to answer questions about the framework, Python packaging, or running Python libraries on mobile."}
{"instruction": "Were you one of the 47,000 hacked by litellm?", "input": "", "output": "Were you one of the 47,000 hacked by litellm?\nOn Monday I posted that litellm 1.82.7 and 1.82.8 on PyPI contained credential-stealing malware (we were the first to disclose, and PyPI credited our report). To figure out how destructive the attack actually was, we pulled every package on PyPI that declares a dependency on litellm and checked their version specs against the compromised versions (using the specs that existed at the time of the attack, not after packages patched.)\n\nOut of 2,337 dependent packages: 59% had lower-bound-only constraints, 16% had upper bounds that still included 1.82.x, and 12% had no constraint at all. Leaving only 12% that were safely pinned. Analysis: [https://futuresearch.ai/blog/litellm-hack-were-you-one-of-the-47000/](https://futuresearch.ai/blog/litellm-hack-were-you-one-of-the-47000/)\n\n47,000 downloads happened in the 46-minute window. 23,142 were pip installs of 1.82.8 (the version with the .pth payload that runs during pip install, before your code even starts.)\n\nWe built a free checker to look up whether a specific package was exposed: [https://futuresearch.ai/tools/litellm-checker/](https://futuresearch.ai/tools/litellm-checker/)"}
{"instruction": "What are some Python automations you built for your life?", "input": "", "output": "What are some Python automations you built for your life?\nWhat Python scripts/projects did you built to use on a day to day basis? Or maybe someone else built it, but it’s useful for your personal life in some way\n\nI think the “projects ideas” thread is really missing those useful opportunities\n\nI myself thought about automating tax calculations, but still didn’t take the time to do it hah"}
{"instruction": "Pandas 3.0.0 is there", "input": "", "output": "Pandas 3.0.0 is there\nSo finally the big jump to 3 has been done. Anyone has already tested in beta/alpha? Any major breaking change? Just wanted to collect as much info as possible :D"}
{"instruction": "I just found a Python script I wrote 3 years ago…", "input": "", "output": "I just found a Python script I wrote 3 years ago…\n…with zero comments, no docstrings, variable names like df2\\_final\\_FINAL\\_v3 and it’s somehow still running in production.\n\nI don’t remember writing it or  deploying it. Nobody knows it exists except the one analyst who emails me if it stops working.\n\nPlease tell me I’m not alone."}
{"instruction": "When did destructive criticism become normalized on this sub?", "input": "", "output": "When did destructive criticism become normalized on this sub?\nIt’s been a while since r/Python posts popped up on my feed. It’s coming up more recently. I’m noticing a shocking amount of toxicity on people’s project shares that I didn’t notice in the past. Any attempt to call out this toxicity is met with a wave of downvotes.\n\nFor those of you who have been in the Reddit echo chamber a little too long, let me remind you that it is not normal to mock/tease/tear down the work that someone did on their own free time for others to see or benefit from. It \\*is\\* normal to offer advice, open issues, offer reference work to learn from and ask questions to guide the author in the right direction.\n\nThis is an anonymous platform. The person sharing their work could be a 16 year old who has never seen a production system and is excited about programming, or a 30 yoe developer who got bored and just wanted to prove a concept, also in their free time. It does not make you a better to default to tearing someone down or mocking their work.\n\nYou poison the community as a whole when you do so. I am not seeing behavior like this as commonly on other language subs, otherwise I would not make this post. The people willing to build in public and share their sometimes unpolished work is what made tech and the Python ecosystem what it is today, in case any of you have forgotten."}
{"instruction": "After the supply chain attack, here are some litellm alternatives", "input": "", "output": "After the supply chain attack, here are some litellm alternatives\nlitellm versions 1.82.7 and 1.82.8 on PyPI were compromised with credential-stealing malware.\nAnd here are a few open-source alternatives:\n1. Bifrost: Probably the most direct litellm replacement right now. Written in Go, claims \\~50x faster P99 latency than litellm. Apache 2.0 licensed, supports 20+ providers. Migration from litellm only requires a one-line base URL change.\n2. Kosong: An LLM abstraction layer open-sourced by Kimi, used in Kimi CLI. More agent-oriented than litellm. it unifies message structures and async tool orchestration with pluggable chat providers. Supports OpenAI, Anthropic, Google Vertex and other API formats.\n3. Helicone: An AI gateway with strong analytics and debugging capabilities. Supports 100+ providers. Heavier than the first two but more feature-rich on the observability side."}
{"instruction": "CVE-[PHONE]: A Maintainer's Perspective", "input": "", "output": "CVE-[PHONE]: A Maintainer's Perspective\nThis is my reply to the vulnerability CVE-[PHONE]:\n\n[https://marcelotryle.com/blog/2026/05/28/cve-[PHONE]-a-maintainers-perspective](https://marcelotryle.com/blog/2026/05/28/cve-[PHONE]-a-maintainers-perspective)"}
{"instruction": "I Fixed python autocomplete", "input": "", "output": "I Fixed python autocomplete\nWhen I opened vscode, and typed \"os.\", it showed me autocomplete options that I almost never used, like `os.abort` or `os.CLD_CONTINUED`, Instead of showing me actually used options, like path or remove. So I created a hash table (not AI, fast lookup) of commonly used prefixes, forked ty, and fixed it.\n\n**What My Project Does:** provide better sorting for python autosuggestion\n\n**Target Audience:** just a simple table, ideally would be merged into LSP\n\n**Comparison:** AI solutions tends to be slower, and CPU-intensive. using table lookup handle the unknown worse, but faster\n\nBlog post: [https://matan-h.com/better-python-autocomplete](https://matan-h.com/better-python-autocomplete) | Repo: [https://github.com/matan-h/pyhash-complete](https://github.com/matan-h/pyhash-complete)"}
{"instruction": "After 25+ years using ORMs, I switched to raw queries + dataclasses. I think it's the move.", "input": "", "output": "After 25+ years using ORMs, I switched to raw queries + dataclasses. I think it's the move.\nI've been an ORM/ODM evangelist for basically my entire career. But after spending serious time doing agentic coding with Claude, I had a realization: AI assistants are dramatically better at writing native query syntax than ORM-specific code. PyMongo has 53x the downloads of Beanie, and the native MongoDB query syntax is shared across Node, PHP, and tons of other ecosystems. The training data gap is massive.\n\nSo I started what I'm calling the **Raw+DC pattern** (aka Raw Dog): raw database queries with Python dataclasses at the data access boundary. You still get type safety, IDE autocompletion, and type checker support. But you drop the ORM dependency risk (RIP mongoengine, and Beanie is slowing down), get near-raw performance, and your AI assistant actually knows what it's doing.\n\nThe \"conversion layer\" is just a `from_doc()` function mapping dicts to dataclasses. It's exactly the kind of boilerplate AI is great at generating and maintaining.\n\nI wrote up the full case with benchmarks and runnable code here: [https://mkennedy.codes/posts/going-raw-dog-on-the-database/](https://mkennedy.codes/posts/going-raw-dog-on-the-database/)\n\nCurious what folks think. Anyone else trending this direction?"}
{"instruction": "Niquests 3.16 — Bringing 'uv-like' performance leaps to Python HTTP", "input": "", "output": "Niquests 3.16 — Bringing 'uv-like' performance leaps to Python HTTP\nRecently, an acquaintance showed me their production logs, and I honestly didn't believe them at first. They claimed Niquests was essentially \"ridiculing\" their previous HTTP performance at scale.\n\nThey had migrated from httpx → aiohttp → Niquests. Even as the author, I was skeptical that we could beat established async giants by that wide of a margin until we sat down and reviewed the real-world cluster data.\n\nThere are no words to describe how satisfying the difference is, so I made a visualization instead:\n\n[Benchmark GIF](https://i.postimg.cc/CLxGykJL/niquests.gif)\n\n_The Secret:_ When under pressure, Niquests pulls ahead because it handles connections like a modern web browser. Instead of opening a flood of connections, it leverages true HTTP/2+ multiplexing to load-balance requests over a limited number of established connections.\n\nThe best part? It achieves this while remaining pure Python (with optional extensions for extra speed, but they aren't required).\n\nWe just hit 1.7M downloads/month. If you are looking for that \"uv-like\" speed without leaving the comfort of Python, give it a spin.\n\n### What My Project Does\n\nNiquests 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.\n\n### Target Audience\n\nIt is a production ready solution. So everyone is potentially concerned.\n\n### Comparison\n\nNiquests 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..)\n\nProject page: https://github.com/jawah/niquests"}
{"instruction": "A Modern Python Stack for Data Projects : uv, ruff, ty, Marimo, Polars", "input": "", "output": "A Modern Python Stack for Data Projects : uv, ruff, ty, Marimo, Polars\nI put together a template repo for Python data projects (linked in the article) and wrote up the “why” behind the tool choices and trade-offs.\n\n[https://www.mameli.dev/blog/modern-data-python-stack/](https://www.mameli.dev/blog/modern-data-python-stack/)\n\nTL;DR stack in the template:\n\n* uv for project + env management\n* ruff for linting + formatting\n* ty as a newer, fast type checker\n* Marimo instead of Jupyter for reactive, reproducible notebooks that are just .py files\n* Polars for local wrangling/analytics\n\nCurious what others are using in 2026 for this workflow, and where this setup falls short"}
{"instruction": "How I went down a massive rabbit hole and ended up building 4 libraries", "input": "", "output": "How I went down a massive rabbit hole and ended up building 4 libraries\nA few months ago, I was in between jobs and hacking on a personal project just for fun. I built one of those automated video generators using an LLM. You know the type: the LLM writes a script, TTS narrates it, stock footage is grabbed, and it's all stitched together. Nothing revolutionary, just a fun experiment.\n\nI hit a wall when I wanted to add subtitles. I didn't want boring static text; I wanted styled, animated captions (like the ones you see on social media). I started researching Python libraries to do this easily, but I couldn't find anything \"plug-and-play.\" Everything seemed to require a lot of manual logic for positioning and styling.\n\nDuring my research, I stumbled upon a YouTube video called *\"Shortrocity EP6: Styling Captions Better with MoviePy\"*. At around the 44:00 mark, the creator said something that stuck with me: *\"I really wish I could do this like in CSS, that would be the best.\"*\n\nThat was the spark. I thought, *why not?* Why not render the subtitles using HTML/CSS (where styling is easy) and then burn them into the video?\n\nI implemented this idea using Playwright (using a headless browser) to render the HTML+CSS and then get the images. It worked, and I packaged it into a tool called **pycaps**. However, as I started testing it, it just felt wrong. I was spinning up an entire, heavy web browser instance just to render a few words on a transparent background. It felt incredibly wasteful and inefficient.\n\nI spent a good amount of time trying to optimize this setup. I implemented aggressive caching for Playwright and even wrote a custom rendering solution using OpenCV inside `pycaps` to avoid MoviePy and speed things up. It worked, but I still couldn't shake the feeling that I was using a sledgehammer to crack a nut.\n\nSo, I did what any reasonable developer trying to avoid \"real work\" would do: I decided to solve these problems by building my own dedicated tools.\n\nFirst, weeks after releasing `pycaps`, I couldn't stop thinking about generating text images without the overhead of a browser. That led to **pictex**. Initially, it was just a library to render text using Skia (PICture + TEXt). Honestly, that first version was enough for what `pycaps` needed. But I fell into another rabbit hole. I started thinking, *\"What about having two texts with different styles? What about positioning text relative to other elements?\"* I went way beyond the original scope and integrated Taffy to support a full Flexbox-like architecture, turning it into a generic rendering engine.\n\nThen, to connect my original CSS templates from `pycaps` with this new engine, I wrote **html2pic**, which acts as a bridge, translating HTML/CSS directly into `pictex` render calls.\n\nFinally, I went back to my original AI video generator project. I remembered the custom OpenCV solution I had hacked together inside `pycaps` earlier. I decided to extract that logic into a standalone library called **movielite**. Just like with `pictex`, I couldn't help myself. I didn't simply extract the code. Instead, I ended up over-engineering it completely. I added Numba for JIT compilation and polished the API to make it a generic, high-performance video editor, far exceeding the simple needs of my original script.\n\n**Long story short:** I tried to add subtitles to a video, and I ended up maintaining four different open-source libraries. The original \"AI Video Generator\" project is barely finished"}
{"instruction": "Astral's python distribution is fast", "input": "", "output": "Astral's python distribution is fast\nBy our measurements, python-build-standalone is now the fastest CPython distribution across major platforms. It's 10% faster than Homebrew's CPython, and 18% faster than the official 3.14 docker image.\n\nThis is mostly due to how python-build-standalone itself is built:\n\n* using a modern Clang lets us turn on tail-call optimizations in the interpreter\n* with PGO, LTO, and BOLT\n* with libpython statically linked into the interpreter executable\n\nOur goal is to ship the fastest Python interpreter to anyone using uv, by default.\n\nCheck out [BENCHMARKS.md](https://github.com/astral-sh/python-build-standalone/blob/91f0cd0976871b98eac75f80ebf237962aee6316/BENCHMARKS.md) in the repo for more details, including the methodology behind the above."}
{"instruction": "Pandas vs Polars in production — has anyone fully switched, and was it worth the migration?", "input": "", "output": "Pandas vs Polars in production — has anyone fully switched, and was it worth the migration?\nFor those who have actually used Polars in production, did you fully switch from Pandas or use both depending on the task?"}
{"instruction": "OpenAI just announced “Prism.” Our project is Prismer, so we’re open-sourcing everything now", "input": "", "output": "OpenAI just announced “Prism.” Our project is Prismer, so we’re open-sourcing everything now\nHi r/Python,\n\nWe’ve been building Prismer for a while now—an all-in-one platform for AI for Science. I’ll be honest: it’s been a rough journey. We iterated through version after version, but we just weren't getting the traction we hoped for.\n\nThen OpenAI announced \"Prism,\" and it felt like a sign. We realized that the future of AI4S shouldn't be locked inside a closed product. So, we’ve decided to push our entire Python codebase to GitHub and pivot to a modular, community-driven approach.\n\n**What My Project Does**\n\nPrismer is a research platform designed to bridge the gap between reading scientific papers and executing their code.\n\n* **Paper-to-Code Pipeline:** It automates the extraction of logic from research papers to help researchers run experiments faster.\n* **Modular AI4S Tools:** We are breaking down our \"all-in-one\" features into modular components (like PDF-to-Python parsers and specialized scientific agents) that devs can plug into their own workflows.\n\n**Target Audience**\n\n* Researchers tired of papers they can't reproduce.\n* Python Developers who want to build modular AI tools for science.\n* Anyone who feels that modern research tools are too fragmented and exhausting.\n\n**Comparison：**\n\n>Vs. OpenAI Prism We aren't a general chatbot; we are a specialized workflow for the scientific ecosystem.\n\nIf you’re a Python dev or a researcher who’s tired of the friction in reproducing experiments, I’d love for you to check out our work. We’re essentially starting over from the code up, and any feedback on our approach would mean a lot.\n\n[`https://github.com/Prismer-AI/Prismer`](https://github.com/Prismer-AI/Prismer)\n\nThanks for letting me share our story and our pivot."}
{"instruction": "Reaching 100% Type Coverage by Deleting Unannotated Code", "input": "", "output": "Reaching 100% Type Coverage by Deleting Unannotated Code\nOn 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.\n\nBut one question kept coming up: What would it take to reach 100% type coverage?\n\nToday, we're excited to share a breakthrough ;-)\n\nLink to full blog: https://pyrefly.org/blog/100-percent-type-coverage/"}
{"instruction": "Benchmarked every Python optimization path I could find, from CPython 3.14 to Rust", "input": "", "output": "Benchmarked every Python optimization path I could find, from CPython 3.14 to Rust\nTook n-body and spectral-norm from the Benchmarks Game plus a JSON pipeline, and ran them through everything: CPython version upgrades, PyPy, GraalPy, Mypyc, NumPy, Numba, Cython, Taichi, Codon, Mojo, Rust/PyO3.\n\nSpent way too long debugging why my first Cython attempt only got 10x when it should have been 124x. Turns out Cython's \\*\\* operator with float exponents is 40x slower than libc.math.sqrt() with typed doubles, and nothing warns you.\n\nGraalPy was a surprise  -  66x on spectral-norm with zero code changes, faster than Cython on that benchmark.\n\nPost: [https://cemrehancavdar.com/2026/03/10/optimization-ladder/](https://cemrehancavdar.com/2026/03/10/optimization-ladder/)\n\nFull code at [https://github.com/cemrehancavdar/faster-python-bench](https://github.com/cemrehancavdar/faster-python-bench)\n\nHappy to be corrected — there's an \"open a PR\" link at the bottom."}
{"instruction": "PDF Oxide -- Fast PDF library for Python with engine in Rust (0.8ms mean, MIT/Apache license)", "input": "", "output": "PDF Oxide -- Fast PDF library for Python with engine in Rust (0.8ms mean, MIT/Apache license)\npdf\\_oxide is a PDF library for text extraction, markdown conversion, PDF creation, OCR. Written in Rust, Python bindings via PyO3. MIT licensed.\n\n        pip install pdf_oxide\n\n        from pdf_oxide import PdfDocument\n        doc = PdfDocument(\"paper.pdf\")\n        text = doc.extract_text(0)\n\nGitHub: [https://github.com/yfedoseev/pdf\\_oxide](https://github.com/yfedoseev/pdf_oxide)\nDocs: [https://oxide.fyi](https://oxide.fyi)\n\nWhy this exists: I needed fast text extraction with a permissive license. PyMuPDF is fast but AGPL, rules it out for a lot of commercial work. pypdf is MIT but 15x slower and chokes on \\~2% of files. pdfplumber is great at tables but not at batch speed.\n\nSo I read the PDF spec cover to cover (\\~1,000 pages) and wrote my own. First version took 23ms per file. Profiled it, found an O(n^(2)) page tree traversal -- a 10,000 page PDF took 55 seconds. Cached it into a HashMap, got it down to 332ms. Kept profiling, kept fixing. Now it's at 0.8ms mean on 3,830 real PDFs.\n\nNumbers on that corpus (veraPDF, Mozilla pdf.js, DARPA SafeDocs):\n\n|Library|Mean|p99|Pass Rate|License|\n|:-|:-|:-|:-|:-|\n|**pdf\\_oxide**|**0.8ms**|**9ms**|**100%**|**MIT**|\n|PyMuPDF|4.6ms|28ms|99.3%|AGPL-3.0|\n|pypdfium2|4.1ms|42ms|99.2%|Apache-2.0|\n|pdftext|7.3ms|82ms|99.0%|GPL-3.0|\n|pypdf|12.1ms|97ms|98.4%|BSD-3|\n|pdfminer|16.8ms|124ms|98.8%|MIT|\n|pdfplumber|23.2ms|189ms|98.8%|MIT|\n|markitdown|108.8ms|378ms|98.6%|MIT|\n\nGive it a try, let me know what breaks.\n\n**What My Project Does**\n\nRust PDF library with Python bindings. Extracts text, converts to markdown and HTML, creates PDFs, handles encrypted files, built-in OCR. MIT licensed.\n\n**Target Audience**\n\nAnyone who needs to pull text out of PDFs in Python without AGPL restrictions, or needs speed for batch processing.\n\n**Comparison**\n\n5-30x faster than other text extraction libraries on a 3,830-PDF corpus. PyMuPDF is more mature but AGPL. pdfplumber is better at tables. pdf\\_oxide is faster with a permissive license."}
{"instruction": "What's new in Python 3.15?", "input": "", "output": "What's new in Python 3.15?\nhttps://docs.python.org/3.15/whatsnew/3.15.html\n\n> Summary – Release highlights\n\n> Python 3.15 will be the latest stable release of the Python programming language, with a mix of changes to the language, the implementation, and the standard library. The biggest changes include lazy imports, frozendict and sentinel builtins, UTF-8 as the default encoding, unpacking in comprehensions, and a stable ABI for free-threaded builds.\n\n> The library changes include a new profiling package with Tachyon, a high-frequency statistical sampling profiler, more color in command-line output, as well as the usual deprecations and removals, and improvements in user-friendliness and correctness.\n\n> This article doesn’t attempt to provide a complete specification of all new features, but instead gives a convenient overview. For full details refer to the documentation, such as the Library Reference and Language Reference. To understand the complete implementation and design rationale for a change, refer to the PEP for a particular new feature; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented."}
{"instruction": "pandas 3 is the most significant release in 10 years", "input": "", "output": "pandas 3 is the most significant release in 10 years\nI asked in a couple of talks I gave about pandas 3 which was the biggest change in pandas in the last 10 years  and most people didn't know what to answer, just a couple answered Arrow, which in a way is more an implementation detail than a change.\n\npandas 3 is not that different being honest, but it does introduce a couple of small but very significant changes:\n\n\\- The introduction of pandas.col(), so lambda shouldn't be much needed in pandas code\n\n\\- The completion of copy-on-write, which makes all the \\`df = df.copy()\\` not needed anymore\n\nI wrote a blog post to show those two changes and a couple more in a practical way with example code: https://datapythonista.me/blog/whats-new-in-pandas-3"}
{"instruction": "Polars + uv + marimo (glazing post - feel free to ignore).", "input": "", "output": "Polars + uv + marimo (glazing post - feel free to ignore).\nI don't work with a lot of python folk (all my colleagues in accademia use R) so I'm coming here to get to gush about some python.\n\nMoving from jupyter/quarto + pandas + poetry for marimo + polars + uv has been absolutely amazing. I'm definitely not a better coder than I was but I *feel* so much more productive and excited to spin up a project.\n\nI'm still learning a lot a bout polars (`.having()` was today's moment of \"Jesus that's so *nice*\") and so the enjoyment of learning is certainly helping, but I had a spare 20 minutes and decided to write up something to take my weight data (I'm a tubby sum'bithch who's trying to do something about it) and write up a little dash board so I can *see* my progress on the screen and it was just soooo fast and easy. I could do it in the old stack quite fast, but this was almost seamless. As someone from a non-cs background and self taught, I've never felt that in control in a project before.\n\nSorry for the rant, please feel free to ignore, I just wanted to express my thanks to the folk who made the tools (on the off chance they're in this sub every now and then) and to do so to people who actually know what I'm talking about."}
{"instruction": "Appreciation to Hynek Schlawack", "input": "", "output": "Appreciation to Hynek Schlawack\nThis guy is kind of my mentor in Python and open-source. He definitely loves programming. He has been an importtant Python core maintainer, and published some successful libraries like **attrs** and **structlog** for improving codebases legibility and structure, he also has a high value series in his youtube channel about how to package python applications in a extremely clean way by using **uv** (https://www.youtube.com/watch?v=mFyE9xgeKcA).\n\nWhat I also love from him is his minimalism and simplicity. In a world of tones of lines of AI-generated code per-day, he has recently published **pgbg**, a new python library consisting in 7 files, very little code, that emerges from a deep understanding of how background processing works in python and the gaps on it. These type of low-abstraction level projects are the ones on which tones of big projects rely. Definitely highly valuable."}
{"instruction": "Starlette 1.0.0rc1 is out!", "input": "", "output": "Starlette 1.0.0rc1 is out!\nAfter almost 8 years since Tom Christie created Starlette in June 2018, the first release candidate for 1.0 is finally here.\n\nStarlette is downloaded almost 10 million times a day, serves as the foundation for FastAPI, and has inspired many other frameworks. In the age of AI, it also plays an important role as a dependency of the Python MCP SDK.\n\nThis release focuses on removing deprecated features marked for removal in 1.0.0, along with some last minute bug fixes.\n\nIt's a release candidate, so feedback is welcome before the final 1.0.0 release.\n\n\\`pip install starlette==1.0.0rc1\\`\n\n\\- Release notes: [https://www.starlette.io/release-notes/](https://www.starlette.io/release-notes/)\n\\- GitHub release: [https://github.com/Kludex/starlette/releases/tag/1.0.0rc1](https://github.com/Kludex/starlette/releases/tag/1.0.0rc1)"}
{"instruction": "New Humble Bundle of Python ebooks benefiting the Python Software Foundation", "input": "", "output": "New Humble Bundle of Python ebooks benefiting the Python Software Foundation\nPay at least $36 for 15 ebooks from No Starch Press benefiting [the PSF](https://www.python.org/psf-landing/): https://www.humblebundle.com/books/python-good-stuff-no-starch-books\n\nHello, I'm Al Sweigart, author of a few books in the bundle. Here's some info about them:\n\n* *Automate the Boring Stuff with Python* - I wrote this to be a programming book for office workers who wanted to escape Excel. It's a book for complete beginners with no coding experience, or for folks who want to skip to Part 2 and learn about several useful packages in the Python ecosystem for web scraping, graph generation, image manipulation, text-to-speech, OCR, regex, sending mobile notifications, and more. *Automate* is now in it's third edition.\n\n* *Cracking Codes with Python* - This was the third book I wrote (and self-published), and then No Starch published a new edition under a new title. (It was previously called Hacking Secret Ciphers with Python.) I had found several \"ciphers and code breaking\" books that discussed ciphers ([The Code Book: The Science of Secrecy from Ancient Egypt to Quantum Cryptography](https://en.wikipedia.org/wiki/The_Code_Book) by Simon Singh is great) but I didn't find any books on writing code to do the code breaking. I wanted Python programs you could literally run on ciphertext that would actually work. Writing this book was a lot of fun. It's also aimed at completely new programmers, using encryption and code breaking programs as the example programming projects.\n\n* *The Big Book of Small Python Projects* - As a kid I loved books like [BASIC Computer Games](https://www.atariarchives.org/basicgames/) that just listed the source code for actual programs you could run. I learned way more from having these small examples, so I wanted an updated version of this. (Admittedly, a *lot* of those BASIC games were buggy or just not fun.) There are 81 programs that use text-based user interfaces (TUI), not out of old-school nostalgia but because it's really helpful to learners to have the program source code and program output be the same medium: text. Like, you can look at the text output and find the `print()` call that caused it. It makes coding less abstract.\n\n(Note that my books are released under a Creative Commons license and can be found online, but these ebooks have much nicer formatting than the HTML pages on my website.)\n\nNo Starch Press is my publisher, but I genuinely do love their books. The ones in this bundle that are on my to-read list that I'm especially excited about:\n\n* *Practical Deep Learning: 2nd Edition* - I've been wanting to read this since the first edition, especially now that I'm diving into LLMs more. This book doesn't shy away from technical details but it's not a textbook: there's actual practical information here.\n\n* *Make Python Talk* - I've already read this and used some of it as the basis for a PyCon talk on text-to-speech and speech recognition. This is stuff that was really unreliable twenty years ago, but these days it's so easy to add it to your Python scripts with just a few lines of code.\n\n* *Computer Science from Scratch* - One of my biggest gripes with CS education is that they often talk about concepts in some abstract way on a whiteboard or in Powerpoint slides, and they don't just give you code you can play with. I'm really interested in diving into this one.\n\n* *Python for Excel Users* - My *Automate* book touches"}
{"instruction": "I built a tensor protocol that outperforms Arrow (18x) and gRPC (13x) using zero-copy mapping memory", "input": "", "output": "I built a tensor protocol that outperforms Arrow (18x) and gRPC (13x) using zero-copy mapping memory\nI wanted to share **Tenso**, a library I wrote to solve a bottleneck in my distributed ML pipeline.\n\n**The Problem:** I needed to stream large tensors between nodes (for split-inference LLMs).\n\n* **Pickle** was too slow and unsafe.\n* **SafeTensors** burned 40% CPU just parsing JSON headers.\n* **Apache Arrow** is amazing, but for pure tensor streaming, the PyArrow wrappers introduced significant overhead (\\~1.1ms per op vs my target of <0.1ms).\n\n**The Insight:** You don't always need Rust or C++ for speed. You just need to respect the CPU cache. Modern CPUs (AVX-512) love 64-byte aligned memory. If your data isn't aligned, the CPU has to copy it. If it is aligned, you can map it instantly.\n\n**What My Project Does**\n\nI implemented a protocol using Python's built-in `struct` and `memoryview` that forces all data bodies to start at a **64-byte boundary**.\n\nBecause the data is aligned on the wire, I can cast the bytes directly to a NumPy array (`np.frombuffer`) without the OS or Python having to copy a single byte.\n\n**Comparison Benchmarks (Mac M4 Pro, Python 3.12):**\n\n* **Deserialization:** \\~0.06ms vs Arrow's 1.15ms (**18x speedup**).\n* **gRPC Throughput:** 13.7x faster than standard Protobuf when used as the payload handler.\n* **CPU Usage:** Drops to **0.9%** (idle) because there is no parsing logic, just pointer arithmetic.\n\n**Other Features:**\n\n* **GPU Support:** Reads directly from the socket into pinned memory for CuPy/Torch/JAX (bypassing CPU overhead).\n* **AsyncIO:** Native `async def` readers/writers.\n\nIt is build for restraint resource environment or high-throughput requirement pipeline\n\n**Repo:** [https://github.com/Khushiyant/tenso](https://github.com/Khushiyant/tenso)\n\n**Pip:** `pip install tenso`"}
{"instruction": "Announcing Kreuzberg v4", "input": "", "output": "Announcing Kreuzberg v4\nHi Peeps,\n\nI'm excited to announce [Kreuzberg](https://github.com/kreuzberg-dev/kreuzberg) v4.0.0.\n\n## What is Kreuzberg:\n\nKreuzberg is a document intelligence library that extracts structured data from 56+ formats, including PDFs, Office docs, HTML, emails, images and many more. Built for RAG/LLM pipelines with OCR, semantic chunking, embeddings, and metadata extraction.\n\nThe new v4 is a ground-up rewrite in Rust with a bindings for 9 other languages!\n\n## What changed:\n\n- **Rust core**: Significantly faster extraction and lower memory usage. No more Python GIL bottlenecks.\n- **Pandoc is gone**: Native Rust parsers for all formats. One less system dependency to manage.\n- **10 language bindings**: Python, TypeScript/Node.js, Java, Go, C#, Ruby, PHP, Elixir, Rust, and WASM for browsers. Same API, same behavior, pick your stack.\n- **Plugin system**: Register custom document extractors, swap OCR backends (Tesseract, EasyOCR, PaddleOCR), add post-processors for cleaning/normalization, and hook in validators for content verification.\n- **Production-ready**: REST API, MCP server, Docker images, async-first throughout.\n- **ML pipeline features**: ONNX embeddings on CPU (requires ONNX Runtime 1.22.x), streaming parsers for large docs, batch processing, byte-accurate offsets for chunking.\n\n## Why polyglot matters:\n\nDocument processing shouldn't force your language choice. Your Python ML pipeline, Go microservice, and TypeScript frontend can all use the same extraction engine with identical results. The Rust core is the single source of truth; bindings are thin wrappers that expose idiomatic APIs for each language.\n\n## Why the Rust rewrite:\n\nThe Python implementation hit a ceiling, and it also prevented us from offering the library in other languages. Rust gives us predictable performance, lower memory, and a clean path to multi-language support through FFI.\n\n## Is Kreuzberg Open-Source?:\n\nYes! Kreuzberg is MIT-licensed and will stay that way.\n\n## Links\n\n- [Star us on GitHub](https://github.com/kreuzberg-dev/kreuzberg)\n- [Read the Docs](https://kreuzberg.dev/)\n- [Join our Discord Server](https://discord.gg/38pF6qGpYD)"}
{"instruction": "[Ann] Pyrefly v1.0 (fast type checker & language server)", "input": "", "output": "[Ann] Pyrefly v1.0 (fast type checker & language server)\nHi, Pyrefly maintainer here. Today we are pleased to share that [Pyrefly](https://pyrefly.org), a fast type checker and language server for Python, has reached stable v1.0 status, meaning we are confident that **Pyrefly is ready for production use**.\n\nPyrefly was first released as an alpha in mid-2025 and followed up with a beta in November of that year. Since then, we have shipped over 60 minor releases: fixing hundreds of bugs, adding the features you’ve been asking for, and improving performance to be one of the fastest tools out there.\n\nThis would not have been possible without our amazing open-source community. To everyone who filed GitHub issues, submitted pull requests, gave us feedback at conferences, or joined us on Discord: thank you. Your contributions shaped this release, we’re grateful for every one of them, and we hope you continue being a part of the journey for future releases too.\n\nWe've published a [blog post](https://pyrefly.org/blog/v1.0/) explaining what v1.0 means exactly, and what's next for Pyrefly.\n\nBelow is a summary of the changes to Pyrefly since the Beta release. The full release notes for v1.0 can be read on our Github.\n\n# Pyrefly v1.0 Release Notes\n\n## Performance Improvements\n\nWe've continued to push Pyrefly's performance since the [speed improvements we shared in February](https://pyrefly.org/blog/2026/02/06/performance-improvements/). Since beta:\n\n- **2–125x faster updated diagnostics** after saving a file (no, that’s not a typo\\!). Thanks to fine-grained dependency tracking and streaming diagnostics, updates now consistently arrive in milliseconds\n- **20–36% faster full type checking** on large projects like PyTorch and Pandas\n- **2–3x faster initial indexing** when Pyrefly first scans your project\n- **40–60% less memory usage** during both indexing and incremental type checking\n\n(Tested on an M4 Macbook Pro using open-source benchmarks from [type\\_coverage\\_py](https://github.com/lolpack/type_coverage_py) and [ty\\_benchmark](https://github.com/astral-sh/ruff/tree/e990dfd069fceef96f797b46161ef78862608449/scripts/ty_benchmark).)\n\nCompare the performance of Pyrefly and other Python type checkers on our regularly updated [benchmarking suite](https://python-type-checking.com/typecheck_benchmark/), which runs against 53 popular Python packages.\n\n---\n\n## Configuration Presets\n\nA new `preset` configuration option provides named bundles of error severities and behavior settings.\n\n| Preset | Description |\n| :---- | :---- |\n| `off` | Silences all diagnostics. Useful for IDE-only users or if you want total control of which errors are enabled. |\n| `basic` | Low-noise, high-confidence diagnostics only (syntax errors, missing imports, unknown names, etc.). Ideal for unconfigured projects or IDE-first users. |\n| `legacy` | For codebases migrating from mypy. Disables checks mypy doesn't have. `pyrefly init` now emits this preset automatically when migrating from a mypy config. |\n| `default` | The standard Pyrefly experience. Equivalent to having no preset. |\n| `strict` | Enables additional strict checks on top of the `default` preset. For users who want to avoid `Any` types in their codebase. |\n\nSee the [configuration docs](https://pyrefly.org/en/docs/configuration/#preset) for details.\n\n---\n\n## Onboarding Experience\n\nWe’ve made improvements to the out-of-the-box experience for projects without a `pyrefly.toml`.\n\n- **Automatic config synthesis** — if you have a"}
{"instruction": "PEP 827 - Type Manipulation has just been published", "input": "", "output": "PEP 827 - Type Manipulation has just been published\n[https://peps.python.org/pep-0827](https://peps.python.org/pep-0827)\n\nThis is a static typing PEP which introduces a huge number of typing [special forms](https://typing.python.org/en/latest/spec/glossary.html#term-special-form) and significantly expands the [type expression grammar](https://typing.python.org/en/latest/spec/annotations.html#type-and-annotation-expressions). The following two examples, taken from the PEP, demonstrate (1) a [unpacking comprehension expression](https://peps.python.org/pep-0827/#unpacked-comprehension) and (2) a [conditional type expression](https://peps.python.org/pep-0827/#conditional-types).\n\n    def select[ModelT, K: typing.BaseTypedDict](\n        typ: type[ModelT],\n        /,\n        **kwargs: Unpack[K]\n    ) -> list[typing.NewProtocol[*[typing.Member[c.name, ConvertField[typing.GetMemberType[ModelT, c.name]]] for c in typing.Iter[typing.Attrs[K]]]]]:\n        raise NotImplementedError\n\n    type ConvertField[T] = (\n        AdjustLink[PropsOnly[PointerArg[T]], T]\n        if typing.IsAssignable[T, Link]\n        else PointerArg[T]\n    )\n\nThere's no canonical discussion place for this yet, but there is a [mypy branch](https://github.com/msullivan/mypy/tree/typemap) with experimental support. See e.g. [a mypy unit test](https://github.com/msullivan/mypy/blob/3bf95c6953f37ead829f61ab289328ecebd83a0a/test-data/unit/check-typelevel-comprehension.test) demonstrating the behaviour."}
{"instruction": "5 standard library modules I use every week that I ignored for too long", "input": "", "output": "5 standard library modules I use every week that I ignored for too long\nNo pip install needed — these are built in and genuinely useful:\n\n**1. `pathlib`** — stop using `os.path`\n\n```python\nfrom pathlib import Path\nfiles = list(Path(\"./data\").glob(\"*.csv\"))\n```\n\n**2. `collections.Counter`** — frequency counting in one line\n\n```python\nfrom collections import Counter\nwords = [\"apple\", \"banana\", \"apple\", \"cherry\", \"banana\", \"apple\"]\nprint(Counter(words))  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})\n```\n\n**3. `itertools.islice`** — read only N lines from a huge file without loading it all\n\n```python\nfrom itertools import islice\nwith open(\"huge.csv\") as f:\n    first_100 = list(islice(f, 100))\n```\n\n**4. `dataclasses`** — clean data structures without boilerplate\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass User:\n    name: str\n    age: int\n    active: bool = True\n```\n\n**5. `contextlib.suppress`** — cleaner than try/except for expected errors\n\n```python\nfrom contextlib import suppress\nwith suppress(FileNotFoundError):\n    os.remove(\"temp.txt\")  # don't care if it doesn't exist\n```\n\nWhat's your most-used stdlib module that beginners tend to skip?"}
{"instruction": "Python is now a first-class language on Cloudflare Workers", "input": "", "output": "Python is now a first-class language on Cloudflare Workers\nCloudflare has made Python Workers generally available, making Python a first-class supported language on its Developer Platform. Developers can now run Python libraries and frameworks such as FastAPI, Django, and Flask while connecting Python applications directly to services, including Workers Al, R2, D1, Durable Objects, Queues, and Workflows. Cloudflare also added native binding support, database connectivity, broader WebAssembly package support, and compatibility with Al libraries like OpenAI, LangChain, and MCP.\n\nRead official blog :- https://blog.cloudflare.com/python-workers-ga/"}
{"instruction": "PEP 823, 824 – None-aware access operators & None-coalescing operators", "input": "", "output": "PEP 823, 824 – None-aware access operators & None-coalescing operators\n# PEP 823 – None-aware access operators\n\n[https://peps.python.org/pep-0823/](https://peps.python.org/pep-0823/)\n\nDiscussions-To: [Discourse thread](https://discuss.python.org/t/pep-823-none-aware-access-operators/109159)\n\nThis PEP proposes adding two new operators.\n\n* The “`None`\\-aware attribute access” operator `?.`\n* The “`None`\\-aware indexing” operator `?[ ]`\n\nThe general idea is to provide access operators which can traverse `None` values without raising exceptions.\n\nBoth operators evaluate the left-hand side, check if it is `not None` and only then evaluate the full expression. They are roughly equivalent to:\n\n    # a.b?.c.d\n    _t.c.d if ((_t := a.b) is not None) else None\n\n    # a.b?[c].d\n    _t[c].d if ((_t := a.b) is not None) else None\n\n# PEP 824 – None-coalescing operators\n\n[https://peps.python.org/pep-0824/](https://peps.python.org/pep-0824/)\n\nDiscussions-To: [Discourse thread](https://discuss.python.org/t/pep-824-none-coalescing-operators/109161)\n\nThis PEP proposes adding two new operators.\n\n* The “`None`\\-coalescing” operator `??`\n* The “`None`\\-coalescing assignment” operator `??=`\n\nThe general idea is to provide a conditional operator, similar to `or`, which instead of truthiness, checks for `None` values.\n\nThe “`None`\\-coalescing” operator evaluates the left-hand side, checks whether it is `not None`, and if not, returns the result. If the value is `None`, the right-hand side is evaluated and returned.\n\nThe “`None`\\-coalescing assignment” operator will only assign the right-hand side to the left-hand side if the left-hand side evaluates to `None`.\n\nThey are roughly equivalent to:\n\n    # a ?? b\n    _t if ((_t := a) is not None) else b\n\n    # a ??= b\n    if a is None:\n        a = b"}
{"instruction": "Python 1.0 came out exactly 32 years ago", "input": "", "output": "Python 1.0 came out exactly 32 years ago\nPython 1.0 came out on January 27, 1994; exactly 32 years ago. Announcement here: https://groups.google.com/g/comp.lang.misc/c/_QUzdEGFwCo/m/KIFdu0-Dv7sJ?pli=1"}
{"instruction": "I built calgebra – set algebra for calendars in Python", "input": "", "output": "I built calgebra – set algebra for calendars in Python\nHey r/python! I've been working on a focused library called **calgebra** that applies set operations to calendars.\n\n## What My Project Does\n\ncalgebra lets you compose calendar timelines using set operators: `|` (union), `&` (intersection), `-` (difference), and `~` (complement). Queries are lazy—you build expressions first, then execute via slicing.\n\n**Example – find when a team is free for a 2+ hour meeting:**\n\n```python\nfrom calgebra import day_of_week, time_of_day, hours, HOUR\n\n# Define business hours\nweekend = day_of_week([\"saturday\", \"sunday\"], tz=\"US/Pacific\")\nweekdays = ~weekend\nbusiness_hours = weekdays & time_of_day(start=9*HOUR, duration=8*HOUR, tz=\"US/Pacific\")\n\n# Team calendars (Google Calendar, .ics files, etc.)\nteam_busy = alice | bob | charlie\n\n# One expression to find available slots\nfree_slots = (business_hours - team_busy) & (hours >= 2)\n```\n\n**Features:**\n- Set operations on timelines (union, intersection, difference, complement)\n- Lazy composition – build complex queries, execute via slicing\n- Recurring patterns with RFC 5545 support\n- Filter by duration, metadata, or custom properties\n- Google Calendar read/write integration\n- iCalendar (.ics) import/export\n\n## Target Audience\n\nDevelopers building scheduling features, calendar integrations, or availability analysis. Also well-suited for AI/coding agents as the composable, type-hinted API works nicely as a tool.\n\n## Comparison\n\nMost calendar libraries focus on parsing (icalendar, ics.py) or API access (gcsa, google-api-python-client). calgebra is about *composing* calendars algebraically:\n\n- **icalendar / ics.py**: Parse .ics files → calgebra can *import* from these, then let you query and combine them\n- **gcsa**: Google Calendar CRUD → calgebra wraps gcsa and adds set operations on top\n- **dateutil.rrule**: Generate recurrences → calgebra uses this internally but exposes timelines you can intersect/subtract\n\nThe closest analog is SQL for time ranges, but expressed as Python operators.\n\n**Links:**\n- GitHub: https://github.com/ashenfad/calgebra\n- Video of a calgebra enabled agent: https://youtu.be/10kG4tw0D4k\n\nWould love feedback!"}
{"instruction": "Pulled a PyPI package that was exfiltrating our environment variable", "input": "", "output": "Pulled a PyPI package that was exfiltrating our environment variable\nOur new dev added what looked like a legit package from PyPI and it turned out to be stealing our .env files. Only caught it during code review when someone noticed weird network requests going out to some random IP.\n\nThe package had over 50k downloads and a normal looking name so it seemed totally safe. This has me rethinking our entire approach to dependency management. We've always just pip installed whatever we needed without much verification. Now I'm realizing that's probably naive but also don't know what the alternative is.\n\nScanning every package manually before install would kill our velocity. How do larger teams handle this without slowing down development?"}
{"instruction": "Tracking 13,000 satellites in under 3 seconds from Python", "input": "", "output": "Tracking 13,000 satellites in under 3 seconds from Python\n I've been working on [https://github.com/ATTron/astroz](https://github.com/ATTron/astroz), an orbital mechanics toolkit with Python bindings. The core is written in Zig with SIMD vectorization.\n\n# What My Project Does\n\nastroz is an astrodynamics toolkit, including propagating satellite orbits using the SGP4 algorithm. It writes directly to numpy arrays, so there's very little overhead going between Python and Zig. You can propagate 13,000+ satellites in under 3 seconds.\n\npip install astroz is all you need to get started!\n\n# Target Audience\n\nAnyone doing orbital mechanics, satellite tracking, or space situational awareness work in Python. It's production-ready. I'm using it myself and the API is stable, though I'm still adding more functionality to the Python bindings.\n\n# Comparison\n\nIt's about 2-3x faster than python-sgp4, far and away the most popular sgp4 implementation being used:\n\n|Library|Throughput|\n|:-|:-|\n|astroz|\\~8M props/sec|\n|python-sgp4|\\~3M props/sec|\n\n# Demo & Links\n\nIf you want to see it in action, I put together a live demo that visualizes all 13,000+ active satellites generated from Python in under 3 seconds: [https://attron.github.io/astroz-demo/](https://attron.github.io/astroz-demo/)\n\nAlso wrote a blog post about how the SIMD stuff works under the hood if you're into that, but it's more Zig heavy than Python: [https://atempleton.bearblog.dev/i-made-zig-compute-33-million-satellite-positions-in-3-seconds-no-gpu-required/](https://atempleton.bearblog.dev/i-made-zig-compute-33-million-satellite-positions-in-3-seconds-no-gpu-required/)\n\nRepo: [https://github.com/ATTron/astroz](https://github.com/ATTron/astroz)"}
{"instruction": "What's your default Python project setup in 2026?", "input": "", "output": "What's your default Python project setup in 2026?\nWhen starting something new, do you default to:\n\n* `venv` or `poetry`?\n* `requests` vs `httpx`?\n* `pandas` vs lighter tools?\n* type checking or not?\n\nNot looking for best, just interested in real-world defaults people actually use."}
{"instruction": "Python as you've never seen it before", "input": "", "output": "Python as you've never seen it before\n# What My Project Does\n\n**memory\\_graph** is an open-source educational tool and debugging aid that visualizes Python execution by rendering the **complete program state** (objects, references, aliasing, and the full call stack) as a graph. It helps build the *right mental model* for Python data, and makes tricky bugs much faster to understand.\n\nSome examples that really show its power are:\n\n* [Hash Map](https://memory-graph.com/#codeurl=https://raw.githubusercontent.com/bterwijn/memory_graph/refs/heads/main/src/hash_map.py&timestep=0.2&play)\n* [Binary Tree](https://memory-graph.com/#codeurl=https://raw.githubusercontent.com/bterwijn/memory_graph/refs/heads/main/src/bin_tree.py&timestep=0.2&play)\n* [Copying](https://memory-graph.com/#breakpoints=8&continues=1&timestep=1.0&play)\n* [Recursion](https://memory-graph.com/#codeurl=https://raw.githubusercontent.com/bterwijn/memory_graph/refs/heads/main/src/binary_convert.py&timestep=1.0&play)\n\nGithub repo: [https://github.com/bterwijn/memory\\_graph](https://github.com/bterwijn/memory_graph)\n\n# Target Audience\n\nIn the first place it's for:\n\n* **teachers/TAs** explaining Python’s data model, recursion, or data structures\n* **learners** (beginner → intermediate) who struggle with references / aliasing / mutability\n\nbut supports **any Python practitioner** who wants a better understanding of what their code is doing, or who wants to fix bugs through visualization. Try these [tricky exercises](https://github.com/bterwijn/memory_graph_videos/blob/main/exercises/exercises.md) to see its value.\n\n# Comparison\n\nHow it differs from existing alternatives:\n\n* Compared to **PythonTutor**: **memory\\_graph** runs locally without limits in many different environments and debuggers, and it mirrors the hierarchical structure of data.\n* Compared to print-debugging and debugger tools: **memory\\_graph** shows **aliasing** and the **complete program state**."}
{"instruction": "I built a COBOL verification engine — it proves migrations are mathematically correct", "input": "", "output": "I built a COBOL verification engine — it proves migrations are mathematically correct\nI'm building Aletheia — a tool that verifies COBOL-to-Python migrations are correct. Not with AI translation, but with deterministic verification.\n\nWhat it does:\n\n* ANTLR4 parser extracts every paragraph, variable, and data type from COBOL source\n* Rule-based Python generator using Decimal precision with IBM TRUNC(STD/BIN/OPT) emulation\n* Shadow Diff: ingest real mainframe I/O, replay through generated Python, compare field-by-field. Exact match or it flags the exact record and field that diverged\n* EBCDIC-aware string comparison (CP037/CP500)\n* COPYBOOK resolution with REPLACING and REDEFINES byte mapping\n* CALL dependency crawler across multi-program systems with LINKAGE SECTION parameter mapping\n* EXEC SQL/CICS taint tracking — doesn't mock the database, maps which variables are externally populated and how SQLCODE branches affect control flow\n* ALTER statement detection — hard stop, flags as unverifiable\n* Cryptographically signed reports for audit trails\n* Air-gapped Docker deployment — nothing leaves the bank's network\n\nBinary output: VERIFIED or REQUIRES MANUAL REVIEW. No confidence scores. No AI in the verification pipeline.\n\n190 tests across 9 suites, zero regressions.\n\nI'm looking for mainframe professionals willing to stress-test this against real COBOL. Not selling anything — just want brutal feedback on what breaks."}
{"instruction": "Astral's Pre-built Gpu-enabled wheels", "input": "", "output": "Astral's Pre-built Gpu-enabled wheels\nWe recently released [wheels.astral.sh](https://wheels.astral.sh/), which is a repository of gpu-enabled wheels of popular packages from the pytorch ecosystem. These are useful because building them is super annoying - you have to align versions of pytorch, cuda, python, etc.\n\nThe pre-built wheels were part of the package of pyx, our paid service, and was a major reason many customers subscribed. We decided to open source the build pipelines and host the wheels for free while we sunset the rest of pyx.\n\nThe pipelines are available under the [astral-sh-build github organization](https://github.com/astral-sh-build).\n\nWhile these plug a genuine UX hole around cuda/pytorch wheels, we hope that wheel variants (PEP 817 and 825) will get accepted and implemented soon, which will let these pytorch wheels be hosted properly on PyPI and \"just work\" out of the box for everyone, making wheels.astral.sh obsolete.\n\nFingers crossed."}
{"instruction": "What linter rules make code worse?", "input": "", "output": "What linter rules make code worse?\nFor me, a prime example is [S101](https://docs.astral.sh/ruff/rules/assert/#assert-s101) which bans the use of the `assert` statement.\n\nThe justification is that assertions disappear when Python is run with `-O`, so they should not be used for runtime validation or enforcing interface constraints. That warning is correct, but the rule seems to draw the wrong conclusion from it.\n\nAssertions are still very useful for checking *internal* invariants, i.e. conditions that should already be guaranteed by the program's logic, where failure indicates a bug. Having such assertions is incredibly helpful for debugging.\n\nSo, a blanket ban seems more likely to discourage useful checks than to prevent misuse.\n\nAre there any linter rules you broadly consider more harmful rather than helpful?"}
{"instruction": "Should we standardize docstring formats?", "input": "", "output": "Should we standardize docstring formats?\nIn Rust, docstrings are pretty formalized. They are markdown, and even some of the headings are standard (like an # Errors or # Panics section). The nice thing about this is that it allows websites like docs.rs to build documentation pages for any project without having to interact with different tools for different formats. It also allows LSPs to have only one way of displaying documentation hints.\n\nIn Python, we have a few competing standards. Numpy-style docstrings are probably the most used,  but there’s also a format by Google as well as a few different reST standards. These are nice, and we can set up lints to make sure docstrings stick to the standard. However, in my own personal opinion (feel free to disagree), a single markdown-format standard would help new users write nice docstrings, would enable PyPI (or another provider) to build automatic documentation sites, and give guidance to LSPs and IDEs for how to display documentation. This would include a standard for interlinks, and probably should include some mathml/LaTeX/KaTeX support. Another benefit would be that tools could support better automatic documentation generation and autocomplete, since they wouldn’t be dependent on guessing which standard you’re following.\n\nI’d like to hear what people think about this. I’m thinking about making a PEP, but that might be overkill (or maybe all of you will hate this idea). I think the primary blocker would be adoption, large projects might have to translate docstrings, so there would either have to be some tooling for this or a way to opt-in or opt-out. If this is a bad idea, let me know, just be nice!"}
{"instruction": "PEP 831 – Frame Pointers Everywhere: Enabling System-Level Observability for Python", "input": "", "output": "PEP 831 – Frame Pointers Everywhere: Enabling System-Level Observability for Python\nhttps://peps.python.org/pep-0831/\n\nThis PEP proposes two things:\n\n1. Build CPython with frame pointers by default on platforms that support them. The default build configuration is changed to compile the interpreter with -fno-omit-frame-pointer and -mno-omit-leaf-frame-pointer. The flags are added to CFLAGS, so they apply to the interpreter itself and propagate to C extension modules built against this Python via sysconfig. An opt-out configure flag (--without-frame-pointers) is provided for deployments that require maximum raw throughput.\n\n2. Strongly recommend that all build systems in the Python ecosystem build with frame pointers by default. This PEP recommends that every compiled component that participates in the Python call stack (C extensions, Rust extensions, embedding applications, and native libraries) should enable frame pointers. A frame-pointer chain is only as strong as its weakest link: a single library without frame pointers breaks profiling, debugging, and tracing for the entire process.\n\nFrame pointers are a CPU register convention that allows profilers, debuggers, and system tracing tools to reconstruct the call stack of a running process quickly and reliably. Omitting them (the compiler’s default at -O1 and above) prevents these tools from producing useful call stacks for Python processes, and undermines the perf trampoline support CPython shipped in 3.12.\n\nThe measured overhead is under 2% geometric mean for typical workloads (see Backwards Compatibility for per-platform numbers). Multiple major Linux distributions, language runtimes, and Python ecosystem tools have already adopted this change. No existing PEP covers this topic; CPython issue #96174 has been open since August 2022 without resolution."}
{"instruction": "DuckDB 1.5.0 released", "input": "", "output": "DuckDB 1.5.0 released\nLooks like it was released yesterday:\n\n- https://duckdb.org/2026/03/09/announcing-duckdb-150\n\nInteresting features seem to be the `VARIANT` and `GEOMETRY` types.\n\nAlso, the new `duckdb-cli` module on pypi.\n\n    % uv run -w duckdb-cli duckdb -c \"from read_duckdb('https://blobs.duckdb.org/data/animals.db', table_name='ducks')\"\n    ┌───────┬──────────────────┬──────────────┐\n    │  id   │       name       │ extinct_year │\n    │ int32 │     varchar      │    int32     │\n    ├───────┼──────────────────┼──────────────┤\n    │     1 │ Labrador Duck    │         1878 │\n    │     2 │ Mallard          │         NULL │\n    │     3 │ Crested Shelduck │         1964 │\n    │     4 │ Wood Duck        │         NULL │\n    │     5 │ Pink-headed Duck │         1949 │\n    └───────┴──────────────────┴──────────────┘\n\n- https://pypi.org/project/duckdb-cli/"}
{"instruction": "Built a Nepali calendar computation engine in Python, turns out there's no formula for it", "input": "", "output": "Built a Nepali calendar computation engine in Python, turns out there's no formula for it\n**What My Project Does**\n\nProject Parva is a REST API that computes Bikram Sambat (Nepal's official calendar) dates, festival schedules, panchanga (lunar almanac), muhurta (auspicious time windows), and Vedic birth charts. It derives everything from real planetary positions using pyswisseph rather than serving hardcoded lookup tables. Takes actual lat/lon coordinates so calculations are accurate for any location, not just Kathmandu.\n\n**Target Audience**\n\nDevelopers building apps that need Nepali calendar data programmatically. Could be production use for something like a scheduling app, a diaspora-focused product, or an AI agent that needs grounded Nepali date data. The API is public beta so the contract is stable but not yet v1. There's also a Python SDK if you want to skip the HTTP boilerplate.\n\n**Comparison**\n\nMost existing options are either NPM packages with hardcoded month-length arrays that break outside a fixed year range (usually 2000-2090 BS), or static JSON files someone manually typed from government PDFs. Both approaches fail for future dates and neither accounts for geographic location in sunrise-dependent calculations. Hamro Patro is the dominant consumer app but has no public API, so developers end up writing scrapers that break constantly. Parva computes everything from Swiss Ephemeris, which means it works for any year and any coordinates.\n\n[https://github.com/dantwoashim/Project\\_Parva](https://github.com/dantwoashim/Project_Parva)"}
{"instruction": "How to deal with slop PR's as a maintainer?", "input": "", "output": "How to deal with slop PR's as a maintainer?\nsays you are the maintainer of a small (50-100 stars) library.\n\n You see someone fork your repo, mention one of your issues in his commits, so your are happy, someone taking true interest in your work!\n\nYou take a look at his branch, and there you see pure AI slop, with files at the repo root (not in the src), tests with print statement even tough you use pytest and it's clearly explained in the contributing doc, and purely hallucinated imports like \"from my lib import Foo, Bar\" even tough there's never any mention of these two in the code or the documentation (and thus completely incomprehensible code with subclasses from these hallucinated types, etc...)\n\nhow to best deal with this without appearing hostile?\n\nI want contributors, I'm very happy for anyone taking a look at my work, but at the same time that person has other forks of repos where it just seems to be hunting for \"good first issues\" label, and thus I'm not sure on the value of giving an honest review if it's not clear on wether there's a genuine intention to resolve the issue or just collect cool github points."}
{"instruction": "Supply-chain attacks are happening daily - add at least dependency cooldown to your Python projects.", "input": "", "output": "Supply-chain attacks are happening daily - add at least dependency cooldown to your Python projects.\nThese days, I can't open X anymore without seeing some supply chain attacks on PyPI or NPM. Things are really getting out of hand. One very simple yet effective approach to mitigate them is to use a dependency cooldown. That means that you don't install anything that's too new - e.g., every dependency needs to be at least a week old.\n\nWhy does this work? Because the community usually intercepts them in hours to days. Both uv and poetry support the definition of the cooldown period inside their config. pip is adding as support as well. I use 1 week to be on the safe side. They both support excluding a specific package from the rule so you can still apply critical fixes to dependencies ASAP.\n\nI wrote about that and how to configure uv/poetry in my blog post: [https://jangiacomelli.com/blog/mitigate-supply-chain-attacks-for-python-dependencies/](https://jangiacomelli.com/blog/mitigate-supply-chain-attacks-for-python-dependencies/)\n\nMore about the dependency cooldown concept:\n\n- [https://blog.yossarian.net/2025/11/21/We-should-all-be-using-dependency-cooldowns](https://blog.yossarian.net/2025/11/21/We-should-all-be-using-dependency-cooldowns)\n- [https://simonwillison.net/2025/Nov/21/dependency-cooldowns/](https://simonwillison.net/2025/Nov/21/dependency-cooldowns/)"}
{"instruction": "The Python documentation is now available in Persian", "input": "", "output": "The Python documentation is now available in Persian\nhttps://blog.python.org/2026/09/the-python-documentation-is-now-available-in-persian/\n\n> We’re excited to announce that the Python documentation is now available in\nPersian (فارسی)!\n\n> A huge thank you to everyone who contributed their time and expertise to the translation effort. Community contributions like these help make Python more accessible to people around the world.\n\n> Did you know? Many letters in the Persian script change shape depending on where they appear in a word. A letter may have isolated, initial, medial, and final forms while still representing the same character! See the [W3C’s Arabic & Persian Layout Requirements, section 4.3.1, Joining Forms](https://www.w3.org/TR/alreq/#h_joining_forms), for more information."}
{"instruction": "What is the real use case for Jupyter?", "input": "", "output": "What is the real use case for Jupyter?\nI recently started taking python for data science course on coursera.\n\nfirst lesson is on Jupyter.\n\nAs I understand, it is some kind of IDE which can execute python code. I know there is more to it, thats why it exists.\n\nWhat is the actual use case for Jupyter. If there was no Jupyter, which task would have been either not possible or hard to do?\n\n\nDoes it have its own interpreter or does it use the one I have on my laptop when I installed python?"}
{"instruction": "Cyber Security wants us to use the latest version all the time", "input": "", "output": "Cyber Security wants us to use the latest version all the time\nI have a question. Cybersecurity team wants us to use the latest python version each time. So if a new version comes out we are expected to upgrade to it ASAP. But from my past experience libraries do not always provide support and can also break while making use of new version without proper support. Did you ever encounter this? Any suggestions? This is just frustrating for the team as it’s not always possible to upgrade to the latest version without fully validating every component. I just want to hear your opinions on this?\n\nFYI we mainly use each Python Version within the LTS timeline. And only upgrade when we need to and do not depend on a library that requires older version."}
{"instruction": "PEP 841 – Adding Frozen Syntax to Optimize Immutable Types", "input": "", "output": "PEP 841 – Adding Frozen Syntax to Optimize Immutable Types\n# PEP 841 – Adding Frozen Syntax to Optimize Immutable Types\n\n[https://peps.python.org/pep-0841/](https://peps.python.org/pep-0841/)\n\nDiscussions-To: [Discourse thread](https://discuss.python.org/t/pep-841-adding-frozen-syntax-to-make-immutable-types-optimizable/108219)\n\n# Abstract\n\nThis PEP proposes *frozen display* syntax: `f{1, 2, 3}` evaluates to a [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset), and `f{'a': 1}` evaluates to a `frozendict`. Because immutability is guaranteed by the syntax itself rather than inferred from usage, the compiler can treat frozen displays as first-class citizens of its optimization pipeline: constant displays are folded into a single `LOAD_CONST` with an exact result type at compile time and cached in `.pyc` files."}
{"instruction": "FastAPI Cloud in Public Beta ⚡️", "input": "", "output": "FastAPI Cloud in Public Beta ⚡️\nHey folks! FastAPI Cloud is now in public beta. 🚀\n\nThis is made by the same team building FastAPI (I created FastAPI, we now have an amazing team building all this).\n\nHere's the announcement post: [https://fastapicloud.com/blog/fastapi-cloud-public-beta/](https://fastapicloud.com/blog/fastapi-cloud-public-beta/)\n\n[](https://www.reddit.com/submit/?source_id=t3_1ucz5m8&composer_entry=crosspost_prompt)"}
{"instruction": "Is it normal to forget some very trivial, and repetitive stuff?", "input": "", "output": "Is it normal to forget some very trivial, and repetitive stuff?\nIs it normal to forget really trivial, repetitive stuff? I genuinely forgot the command to install a Python library today, and now I’m questioning my entire career and whether I’m even fit for this. It feels ten times worse because just three days ago, I forgot the `input()` function. Is it just me?"}
{"instruction": "I built a Python UI framework inspired by Streamlit, but with O(1) state updates", "input": "", "output": "I built a Python UI framework inspired by Streamlit, but with O(1) state updates\n\nHey r/Python,\n\nI love Streamlit's simplicity, but the \"full script rerun\" on every interaction drove me crazy. It gets super slow once your app grows, and using `st.cache` everywhere felt like a band-aid.\n\nSo I spent the last few weeks building **Violit**. I wanted something that feels like writing a simple Python script but performs like a modern React app.\n\n**What My Project Does**\n\nViolit is a high-performance Python web framework. It allows you to build interactive web apps using pure Python without the performance penalty of full-page reloads.\n\nIt uses a **\"Zero Rerun\"** architecture based on FastAPI, htmx, and WebSockets. When you interact with a widget (like a button or slider), Violit updates *only* that specific component in **O(1)** time, ensuring no screen flickering and instant feedback. It also supports running your web app into a desktop app (like electron) with a single flag (`--native`).\n\n**Target Audience**\n\n* **Data Scientists & Python Devs:** Who need to build dashboards or internal tools quickly but are frustrated by Streamlit's lag.\n* **Production Use:** It's currently in early Alpha (v0.0.2), so it's best for internal tools, side projects, and early adopters who want to contribute to a faster Python UI ecosystem.\n\n**Comparison**\n\nHere is how Violit differs from existing alternatives:\n\n* **vs. Streamlit:** Violit keeps the intuitive API (90% compatible) but removes the \"Full Script Rerun.\" State updates are O(1) instead of O(N).\n* **vs. Dash:** Violit offers reactive state management without the \"callback hell\" complexity of Dash.\n* **vs. Reflex/NiceGUI:** Violit requires **Zero Configuration**. No Node.js dependency, no build steps. Just `pip install` and run. Plus, it has built-in native desktop support.\n\n**Code Example**\n\n    import violit as vl\n    ​\n    app = vl.App()\n    count = app.state(0)  # Reactive State\n    ​\n    # No rerun! Only the label updates instantly.\n    app.button(\"Increment\", on_click=lambda: count.set(count.value + 1))\n    app.write(\"Count:\", count)\n    ​\n    app.run()\n\n**Link to Source Code**\n\nIt is open source (MIT License).\n\n* **Repo:** [https://github.com/violit-dev/violit](https://github.com/violit-dev/violit)\n* **PyPI:** `pip install violit`\n\nI'd love to hear your feedback!"}
{"instruction": ".pipe() in pandas changed how I write data pipelines", "input": "", "output": ".pipe() in pandas changed how I write data pipelines\n**Been using** `.pipe()` **in pandas lately and it's been a game changer — anyone else?**\n\nI was writing some data transformation code the other day and stumbled across `.pipe()`. Honestly didn't expect much, but it completely changed how I structure my pipelines.\n\nInstead of this mess:\n\n\n`df_final = sort_by_total(calculate_total(filter_by_price(df)))`\n\nYou just write it top to bottom like a recipe:\n\n`df_final = (`\n\n`df`\n\n`.pipe(filter_by_price)`\n\n`.pipe(calculate_total)`\n\n`.pipe(sort_by_total)`\n\n`)`\n\nSame result, way more readable. Each function takes a DataFrame and returns a DataFrame — that's the only rule.\n\nFull example if you want to try it:\n\n`import pandas as pd`\n\n`df = pd.DataFrame({`\n\n`\"product\": [\"Product A\", \"Product B\", \"Product C\", \"Product D\"],`\n\n`\"price\": [20, 150, 230, 100],`\n\n`\"quantity\": [10, 5, 3, 8]`\n\n`})`\n\n`def filter_by_price(df):`\n\n`return df[df[\"price\"] > 100]`\n\n`def calculate_total(df):`\n\n`return df.assign(total_value=df[\"price\"] * df[\"quantity\"])`\n\n`def sort_by_total(df):`\n\n`return df.sort_values(\"total_value\", ascending=False)`\n\n`df_final = (`\n\n`df`\n\n`.pipe(filter_by_price)`\n\n`.pipe(calculate_total)`\n\n`.pipe(sort_by_total)`\n\n`)`\n\nBeen using it a lot for ETL and data cleaning workflows. Makes debugging way easier too — just comment out one `.pipe()` step and you see exactly where things go wrong.\n\nAnyone else using this regularly? Any patterns you've found useful with it?"}
{"instruction": "PyTorch Lightning malware plants a hook in Claude Code's settings.json so it runs on every future se", "input": "", "output": "PyTorch Lightning malware plants a hook in Claude Code's settings.json so it runs on every future se\nTwo versions of \\`lightning\\` (2.6.2 and 2.6.3) were published to PyPI yesterday and yanked same day after Semgrep detected them. Beyond the usual credential-stealing pattern, there's a persistence mechanism worth knowing about if you use Claude Code.\n\nThe malware writes a \\`SessionStart\\` hook to \\`.claude/settings.json\\` with \\`matcher: \"\\*\"\\`. That hook points to a Bun runtime bootstrapper for a 14.8 MB payload. Every time any developer on the machine opens Claude Code - not just in the infected project, but in any project - the hook fires automatically. A parallel hook targets VS Code via \\`.vscode/tasks.json\\` with \\`runOn: folderOpen\\`.\n\nThe exfiltration is four-channel: HTTPS POST to a C2, GitHub commits with \\`EveryBoiWeBuildIsAWormyBoi\\` as the message prefix (searchable on GitHub commit search if you want to check if you're affected), pushing to the victim's own repositories, and a GitHub Actions workflow that dumps all repository secrets via \\`${{ toJSON(secrets) }}\\`.\n\nIf it finds npm publish credentials, it worms into npm by injecting the dropper into every package that token can publish, bumps the patch version, and republishes.\n\nSemgrep's writeup calls this \"among the first documented instances of malware abusing Claude Code's hook system in a real-world attack.\"\n\nIf you've installed anything from PyPI recently on a machine where you use Claude Code, it's worth checking \\`.claude/settings.json\\` for unexpected \\`hooks.SessionStart\\` entries. 2.6.1 is clean."}
{"instruction": "What’s one Python data tool you ignored for too long?", "input": "", "output": "What’s one Python data tool you ignored for too long?\nFor me it was `httpx`. I stuck with `requests` out of habit way longer than I should have.\n\nCurious what tools or libraries others slept on:\n\n* pandas features\n* async tools\n* API clients\n* visualization libs\n\nBonus points if you can explain *why* you avoided it at first."}
{"instruction": "Is := widely used?", "input": "", "output": "Is := widely used?\nI always thought the walrus operator is neat and it makes while loop’s condition clearer. But also it is just a syntactic sugar without anything new. I wonder anyone uses it?"}
{"instruction": "python's free threading is the feature nobody's talking about enough", "input": "", "output": "python's free threading is the feature nobody's talking about enough\nevery python conversation in 2026 is about AI. which is fair, the ecosystem is incredible for ML and the tooling keeps getting better. but free threading (the no-GIL work) might be the most important thing happening to python as a general purpose language and it barely comes up\n\nfor context if you havent followed it closely, python is getting real multithreading. not multiprocessing where you spawn separate processes and deal with serialization overhead, actual shared-memory threads that run in parallel. the thing people have been asking for literally since python existed\n\ni tested it on a data pipeline at work thats CPU bound, parsing and transforming a few million records. with the GIL the threaded version was actually slower than single-threaded because of lock contention. with free threading enabled it scaled almost linearly across 4 cores. same code, just a flag\n\nthe reason i think this matters beyond the benchmarks is that it removes one of the main arguments for reaching for Go or Node for concurrent workloads. \"python cant do real concurrency\" has been true for 30+ years and now it just isnt you know\n\nobviously theres caveats. C extensions need to be updated, some libraries arent thread-safe yet, and you probably shouldnt throw it into production tomorrow. but the trajectory is clear and i feel like the community is sleeping on it because everyone is focused on whether claude or gpt is better at writing pandas code\n\nidk maybe im wrong and everyone is paying attention and i just missed it. but in my circle at least this barely gets mentioned"}
{"instruction": "20 itertools functions, sorted by how often you'd actually reach for them (not the docs order)", "input": "", "output": "20 itertools functions, sorted by how often you'd actually reach for them (not the docs order)\n    itertools is one of those modules everyone imports but most people only use 3-4 functions from. Went through all 20 and sorted them by how often you'd actually reach for each one in real code, not the order they show up in the docs.\n\n|Function|Example|What it does|\n|:-|:-|:-|\n|**chain()**|`chain(it1, it2)`|Concatenates iterables, flattens multiple iterables into a single iterator.|\n|**chain.from\\_iterable()**|`chain.from_iterable(nested)`|Flattens one level of nesting lazily, like `chain(*nested)` without unpacking.|\n|**islice()**|`islice(it, start, stop)`|Slices an iterator, doesn't support negative indices.|\n|**compress()**|`compress('ABCDEF', [1,0,1,0,1,1])`|Filters data by a boolean selector iterable, yields `A, C, E, F`.|\n|**filterfalse()**|`filterfalse(lambda x: x<5, [1,4,6,3,8])`|Yields elements where the predicate is false, opposite of `filter()`.|\n|**starmap()**|`starmap(pow, [(2,5), (3,2)])`|Applies a function with arguments unpacked from each tuple in the iterable.|\n|**pairwise()**|`pairwise([1, 2, 3])`|Returns overlapping pairs of consecutive elements: `(1,2), (2,3)` (3.10+).|\n|**batched()**|`batched(range(10), 3)`|Splits an iterable into fixed-size tuples, last batch may be shorter (3.12+).|\n|**groupby()**|`groupby(items, key=func)`|Groups consecutive elements by key, input must already be sorted by that key.|\n|**accumulate()**|`accumulate(nums, func)`|Running totals or reductions, default is addition, accepts any binary function.|\n|**takewhile()**|`takewhile(pred, it)`|Yields elements while the predicate is true, stops at the first false.|\n|**dropwhile()**|`dropwhile(pred, it)`|Skips elements while the predicate is true, then yields everything remaining.|\n|**tee()**|`tee(iterable, n=2)`|Splits one iterator into n independent iterators, use before the original is consumed.|\n|**zip\\_longest()**|`zip_longest(a, b, fillvalue=None)`|Like `zip()` but continues to the longest input, filling shorter ones with `fillvalue`.|\n|**combinations()**|`combinations(items, r)`|All r-length combinations, order doesn't matter, no repeated elements.|\n|**combinations\\_with\\_replacement()**|`combinations_with_replacement('AB', 2)`|All r-length combinations allowing repeats, yields `AA, AB, BB`.|\n|**permutations()**|`permutations(items, r)`|All r-length permutations, order matters, no repeated elements.|\n|**product()**|`product(a, b)`|Cartesian product, equivalent to nested for-loops.|\n|**count()**|`count(start=0, step=1)`|Infinite counter, useful with `zip()` or `takewhile()`.|\n|**cycle()**|`cycle([1, 2, 3])`|Repeats an iterable infinitely, keeps a copy of all elements in memory.|\n|**repeat()**|`repeat(10, times=3)`|Repeats an object n times, infinite if `times` is omitted.|\n\n    `pairwise` and `batched` are the two most people don't know about, both fixed a \"why am I hand-rolling this\" moment for me. Curious which one on this list you use the least, or if I'm missing one people reach for a lot."}
{"instruction": "I built an interactive Python book that lets you code while you learn (Basics to Advanced)", "input": "", "output": "I built an interactive Python book that lets you code while you learn (Basics to Advanced)\nHey everyone,\n\nI’ve been working on a project called **ThePythonBook** to help students get past the \"tutorial hell\" phase. I wanted to create something where the explanation and the execution happen in the same place.\n\nIt covers everything from your first `print(\"Hello World\")` to more advanced concepts, all within an interactive environment. No setup required—you just run the code in the browser.\n\nCheck it out here: [https://www.pythoncompiler.io/python/getting-started/](https://www.pythoncompiler.io/python/getting-started/)\n\nIt's completely free, and I’d love to get some feedback from this community on how to make it a better resource for beginners!"}
{"instruction": "What small Python scripts or tools have made your daily workflow easier?", "input": "", "output": "What small Python scripts or tools have made your daily workflow easier?\nNot talking about big frameworks or full applications — just **simple Python tools or scripts** that ended up being surprisingly useful in everyday work.\n\nSometimes it’s a tiny automation script, a quick file-processing tool, or something that saves a few minutes every day but adds up over time.\n\nThose small utilities rarely get talked about, but they can quietly become part of your routine.\n\nWould be interesting to hear what **little Python tools** people here rely on regularly and what problem they solve."}
{"instruction": "PEP 747 – Annotating Type Forms is accepted", "input": "", "output": "PEP 747 – Annotating Type Forms is accepted\n[PEP 747](https://peps.python.org/pep-0747/) got [accepted](https://discuss.python.org/t/pep-747-typeexpr-type-hint-for-a-type-expression/55984/103)\n\nThis allows annotating arguments that essentially expect a type annotation like `int | str` or `list[int]`, allowing to annotate functions like:\n\n`def trycast[T](typx: TypeForm[T], value: object) -> T | None: ...`\n\nand the type checker should be able to infer\n\n- `trycast(list[int], [\"1\", \"2\"])  # list[int] | None`\n- `trycast(list[str], (2, 3))  # list[str] | None`"}
{"instruction": "What are your goto lesserknown standard library modules that more Python devs should know about?", "input": "", "output": "What are your goto lesserknown standard library modules that more Python devs should know about?\n Been writing Python for a while now and I keep discovering useful modules hiding in plain sight in the standard library. Things like itertools, collections, and contextlib come up fairly often, but plenty of others seem to fly completely under the radar.\n\nFor example, I only recently started using textwrap regularly for CLI output formatting, and graphlib for topological sorting, which saved me from pulling in an external dependency I didn't actually need.\n\nIt got me thinking about how often we reach for a thirdparty package when the standard library already has something solid built in. Not always the most featurerich solution, but often good enough, with zero install overhead or supply chain concerns. That last part feels increasingly relevant given recent discussions around malicious PyPI packages.\n\nCurious what the community uses. What standard library modules do you find yourself recommending to others that they've never heard of? Doesn't have to be obscure for its own sake, just genuinely underused relative to how useful it is.\n\nWould love to build a bit of a reference list from the responses. Bonus points if you share a concrete use case rather than just the module name, since that tends to make things click for people who've never reached for it before."}
{"instruction": "Astral's endorsements for Python's first Packaging Council", "input": "", "output": "Astral's endorsements for Python's first Packaging Council\nAstral has announced their endorsements for Python's first packaging council elections.\n\n- Read their announcement here - https://astral.sh/blog/python-packaging-council\n- DPO discussion link - https://discuss.python.org/t/ppc-endorsements-from-astral-the-uv-team/\n\nPPC election details:\n\n- https://pyfound.blogspot.com/2026/08/announcing-packaging-council-election.html\n- Nominees (17 nominees for 5 spots) - https://pyfound.blogspot.com/2026/08/announcing-packaging-council-election.html\n\nNote: Voting is currently open and ends on Tuesday, September 15th, 2:00 pm UTC\n\nWhat are your thoughts? The candidates they have nominated are fine, they are/have been heavily involved in packaging in the past."}
{"instruction": "What’s a debugging technique that saved you hours and you wish you’d learned earlier?", "input": "", "output": "What’s a debugging technique that saved you hours and you wish you’d learned earlier?\nI’m curious about the small debugging techniques that make a big difference when working on real projects.For developers with some experience, what debugging technique or habit has saved you the most time?It could be something simple that beginners often overlook.\n\nWhat’s one debugging tip you wish someone had taught you when you were starting out?"}
{"instruction": "We’re creating “AI-assisted” developers who can’t actually code", "input": "", "output": "We’re creating “AI-assisted” developers who can’t actually code\nI need to vent for a minute.\n\nI’m not anti-AI. I use it. It’s useful. It saves time. But the way it’s being used lately in the Python space (and programming in general) is honestly worrying.\n\nI’m seeing more and more projects that look impressive at first glance big repos, fancy README, tons of features but the moment you dig in, it falls apart.\n\n* No understanding of why certain libraries were chosen\n* Massive files with zero structure\n* Random multithreading slapped in “for performance”\n* SQL queries that clearly haven’t been thought through\n* Security completely ignored\n* And the developer can’t explain half of their own code\n\nYou can almost *feel* when a repo is AI-generated. The comments have that polished-but-empty tone. The structure looks clean but soulless. There’s logic, but no intention.\n\nThe biggest issue isn’t AI itself it’s people treating it like a senior engineer instead of a tool. Copy, paste, ship. No debugging discipline. No architecture thinking. No tradeoff analysis.\n\nBefore AI, if you copied something blindly, it usually broke. That friction forced you to learn. Now you can generate 500 lines instantly and if it runs, people assume it’s good.\n\nBut “it runs” is not the same as:\n\n* It scales\n* It’s secure\n* It’s maintainable\n* You understand it\n\nI’m worried we’re normalizing surface-level competence. Projects that look advanced but collapse under real scrutiny.\n\nAI should accelerate developers not replace the thinking part.\n\nCurious if others are noticing this shift, or if I’m just becoming the grumpy old dev yelling at the cloud."}
{"instruction": "Pingram – A Minimalist Telegram Messaging Framework for Python", "input": "", "output": "Pingram – A Minimalist Telegram Messaging Framework for Python\n# What My Project Does\n\nPingram is a lightweight, one-dependency Python library for sending Telegram messages, photos, documents, audio, and video using your bot. It’s focused entirely on outbound alerts, ideal for scripts, bots, or internal tools that need to notify a user or group via Telegram as a free service.\n\nNo webhook setup, no conversational interface, just direct message delivery using HTTPX under the hood.\n\nExample usage:\n\n    from pingram import Pingram\n\n    bot = Pingram(token=\"<your-token>\")\n    bot.message(chat_id=123456789, text=\"Backup complete\")\n\n# Target Audience\n\nPingram is designed for:\n\n* Developers who want fast, scriptable messaging without conversational features\n* Users replacing email/SMS alerts in cron jobs, containers, or monitoring tools\n* Python devs looking for a minimal alternative to heavier Telegram bot frameworks\n* Projects that want to embed notifications without requiring stateful servers or polling\n\nIt’s production-usable for simple alerting use cases but not intended for full-scale bot development.\n\n# Comparison\n\nCompared to python-telegram-bot, Telethon, or aiogram:\n\n* Pingram is <100 LOC, no event loop, no polling, no webhooks — just a clean HTTP client\n* Faster to integrate for one-off use cases like “send this report” or “notify on job success”\n* Easier to audit, minimal API surface, and no external dependencies beyond httpx\n\nIt’s more of a messaging transport layer than a full bot framework.\n\nWould appreciate thoughts, use cases, or suggestions. Repo: [https://github.com/zvizr/pingram](https://github.com/zvizr/pingram)"}
{"instruction": "pip 26.2 - --only-deps, --no-require-hashes, venv isolation, and more!", "input": "", "output": "pip 26.2 - --only-deps, --no-require-hashes, venv isolation, and more!\nHello!\n\nThe pip team recently released pip 26.2. This release is quite large, with features such as:\n\n* Support for Python 3.15\n* Selecting only dependencies (`--only-deps`)\n* Mixing hashed and non-hashable requirements via `--no-require-hashes`\n* Experimental: venv based build isolation (`--use-feature=venv-isolation`)\n* Faster repeated resolves by caching index simple responses\n* Disable `HTTP(S)_PROXY` and similar non-pip specific proxy environment variables via `--no-proxy-env`\n* Separation between regular and build constraint (use `--build-constraint` instead)\n\nFor more details, please consult our changelog: [https://pip.pypa.io/en/stable/news/](https://pip.pypa.io/en/stable/news/). Alternatively, you may consult my release post which goes into greater detail to the highlights of this release: [https://sichard.ca/blog/2026/07/whats-new-in-pip-26.2/](https://sichard.ca/blog/2026/07/whats-new-in-pip-26.2/)\n\nIf you have any questions, you're welcome to ask!"}
{"instruction": "I used C++ and nanobind to build a zero-copy graph engine that lets Python train on 50GB datasets", "input": "", "output": "I used C++ and nanobind to build a zero-copy graph engine that lets Python train on 50GB datasets\nIf you’ve ever worked with massive datasets in Python (like a 50GB edge list for Graph Neural Networks), you know the \"Memory Wall.\" Loading it via Pandas or standard Python structures usually results in an instant 24GB+ OOM allocation crash before you can even do any math.\n\nso I built **GraphZero (v0.2)** to bypass Python's memory overhead entirely.\n\n# What My Project Does\n\nGraphZero is a C++ data engine that streams datasets natively from the SSD into PyTorch without loading them into RAM.\n\nInstead of parsing massive CSVs into Python memory, the engine compiles the raw data into highly optimized binary formats (`.gl` and `.gd`). It then uses POSIX `mmap` to memory-map the files directly from the SSD.\n\nThe magic happens with `nanobind`. I take the raw C++ pointers and expose them directly to Python as zero-copy NumPy arrays.\n\n    import graphzero as gz\n    import torch\n\n    # 1. Mount the zero-copy engine\n    fs = gz.FeatureStore(\"papers100M_features.gd\")\n\n    # 2. Instantly map SSD data to PyTorch (RAM allocated: 0 Bytes)\n    X = torch.from_numpy(fs.get_tensor())\n\n\nDuring a training loop, Python thinks it has a 50GB tensor sitting in RAM. When you index it, it triggers an OS Page Fault, and the operating system automatically fetches *only* the required 4KB blocks from the NVMe drive. The C++ side uses OpenMP to multi-thread the data sampling, explicitly releasing the Python GIL so disk I/O and GPU math run perfectly in parallel.\n\n# Target Audience\n\n* **Who it's for:** ML Researchers, Data Engineers, and Python developers training Graph Neural Networks (GNNs) on massive datasets that exceed their local system RAM.\n* **Project Status:** It is currently in v0.2. It is highly functional for local research and testing (includes a full PyTorch GraphSAGE example), but I am looking for community code review and stress-testing before calling it production-ready.\n\n# Comparison\n\n* **vs. PyTorch Geometric (PyG) / DGL:** Standard GNN libraries typically attempt to load the entire edge list and feature matrix into system memory before pushing batches to the GPU. On a dataset like Papers100M, this causes an instant out-of-memory crash on consumer hardware. GraphZero keeps RAM allocation at 0 bytes by streaming the data natively.\n* **vs. Pandas / Standard Python:** Loading massive CSVs via Pandas creates massive memory overhead due to Python objects. GraphZero uses strict C++ template dispatching to enforce exact `FLOAT32` or `INT64` memory layouts natively, and `nanobind` ensures no data is copied when passing the pointer to Python.\n\nI built this mostly to dive deep into C-bindings, memory management, and cross-platform CI/CD (getting Apple Clang and MSVC to agree on C++20 was a nightmare).\n\nThe repo has a self-contained synthetic example and a training script so you can test the zero-copy mounting locally. I'd love for this community to tear my code apart—especially if you have experience with `nanobind` or high-performance Python extensions!\n\n**GitHub Repo:** [repo](https://github.com/KrishSingaria/graphzero)"}
{"instruction": "Pip 26.2: –only-deps solves 16 years of app deployment hacks", "input": "", "output": "Pip 26.2: –only-deps solves 16 years of app deployment hacks\nThis has been one of my biggest annoyances working with Python and pip when dealing with projects where that are **not meant to be installed as a package**, how do you handle dependencies?\n\nThink projects like application backends, python scripts, REST APIs etc\n\nIf you’ve ever struggled with this, you’re going to love this: a PR by [Sebastian Höffner ](https://github.com/shoeffner)opened [\\#13895](https://github.com/pypa/pip/pull/13895) will add a new global flag to pip such that you can directly install any dependencies in your `pyproject.toml` without installing the package itself.\n\n`pip install --only-deps .`\n\n\nThis is going, for me at least, be a huge boost in the way that I manage and distribute my projects on servers. Vastly simplifying poor manual workarounds that have built up over years.\n\nSince it’s been more than a decade in the making, let’s cover the history of poor Python souls stuck trying to figure out how to install dependencies for their scripts or apps.\n\n\n**This PR is currently slated to land in pip 26.2 which comes out end of July.**\n\nHere's my post about this covering some of the 16 years of workarounds and some posts from StackOverflow / [Python.org](http://Python.org) etc\n\n[https://jamesoclaire.com/2026/07/23/pip-26-2-only-deps-solves-16-years-of-app-deployment-hacks/](https://jamesoclaire.com/2026/07/23/pip-26-2-only-deps-solves-16-years-of-app-deployment-hacks/)"}
{"instruction": "Would it have been better if Meta bought Astral.sh instead?", "input": "", "output": "Would it have been better if Meta bought Astral.sh instead?\nI haven't thought about this too much but I want your thoughts. Not to glaze Meta (since they're a problematic company with issues like privacy), I just think it would be less upsetting if Astral was bought by Meta rather than OpenAI, since they seem to have a better track record for open source software including React & Pytorch. Meta also develops Cinder, a fork of Python for higher performance and work on upstreaming changes. Idk, it seems it would've made more sense if Meta bought Astral and they would do better under them."}
{"instruction": "pip 26.1: experimental support for installing lockfiles + dependency cooldowns!", "input": "", "output": "pip 26.1: experimental support for installing lockfiles + dependency cooldowns!\nHey all,\n\nI'm one of the maintainers of pip. Earlier yesterday, we released pip 26.1.\n\nThe main new feature is ***experimental*** support for `pylock.toml` files ([PEP 751](https://peps.python.org/pep-0751/)) as a requirements source. `pylock.toml` files or URLs can be provided with the `-r / --requirements` options to the commands supporting it.\n\n    pip install -r pylock.toml\n    pip wheel -r pylock.toml\n    pip download -r pylock.toml\n\n***Note****: As conveyed by the experimental warning, keep in mind this feature may evolve significantly or even be removed in favor of another option or command in future pip releases.*\n\nOther notable improvements include:\n\n* Allow `--uploaded-prior-to` to accept a duration in days (e.g., `P7D` for 7 days ago) to support \"Dependency cooldowns\", a strategy of intentionally delaying package updates to give security researchers and package authors time to recover from (ever-increasing) supply chain attacks. See also [William Woodruff's \"We should all be using dependency cooldowns\"](https://blog.yossarian.net/2025/11/21/We-should-all-be-using-dependency-cooldowns)\n* Allow unpinned requirements to use hashes from constraints and allow URL constraints to apply to requirements with extras, removing some of the last roadblocks towards the removal of the legacy resolver\n* Several performance and memory usage improvements to dependency resolution\n* And of course several bug fixes and security fixes\n\nPlease consult our [changelog](https://pip.pypa.io/en/stable/news/) for more information.\n\nYou can also consult my (unofficially official) release blog post for pip 26.1, which discusses the highlights from the release in greater detail: [https://ichard26.github.io/blog/2026/04/whats-new-in-pip-26.1/](https://ichard26.github.io/blog/2026/04/whats-new-in-pip-26.1/)\n\nMany thanks goes to Stéphane, Damian, Pradyun and Paul who all chipped in a significant way to this release. Doubly so to Stéphane who upstreamed support for pylock.toml to the `packaging` library AND added pylock.toml support to pip.\n\n\nEnjoy the new features! We welcome your feedback in the issue tracker."}
{"instruction": "FastIter- Parallel iterators for Python 3.14+ (no GIL)", "input": "", "output": "FastIter- Parallel iterators for Python 3.14+ (no GIL)\nHey! I was inspired by Rust's Rayon library, the idea that parallelism should feel as natural as chaining `.map()` and `.filter()`. That's what I tried to bring to Python with FastIter.\n\n**What My Project Does**\n\nFastIter is a parallel iterators library built on top of Python 3.14's free-threaded mode. It gives you a chainable API - `map`, `filter`, `reduce`, `sum`, `collect`, and more - that distributes work across threads automatically using a divide-and-conquer strategy inspired by Rayon. No `multiprocessing` boilerplate. No pickle overhead. No thread pool configuration.\n\nMeasured on a 10-core system with `python3.14t` (GIL disabled):\n\n| Threads | Simple sum (3M items) | CPU-intensive work |\n|---------|----------------------|-------------------|\n| 4       | 3.7x                 | 2.3x              |\n| 8       | 4.2x                 | 3.9x              |\n| 10      | 5.6x                 | 3.7x              |\n\n**Target Audience**\n\nPython developers doing CPU-bound numeric processing who don't want to deal with the ceremony of `multiprocessing`. Requires `python3.14t` - with the GIL enabled it will be slower than sequential, and the library warns you at import time. Experimental, but the API is stable enough to play with.\n\n**Comparison**\n\nThe obvious alternative is `multiprocessing.Pool` - processes avoid the GIL but pay for it with pickle serialisation and ~50-100ms spawn cost per worker, which dominates for fine-grained operations on large datasets. FastIter uses threads and shared memory, so with the GIL gone you get true parallel CPU execution with none of that cost. Compared to `ThreadPoolExecutor` directly, FastIter handles work distribution automatically and gives you the chainable API so you're not writing scaffolding by hand.\n\n`pip install fastiter` | [GitHub](https://github.com/rohaquinlop/fastiter)"}
{"instruction": "Comparing Python Type Checkers: Typing Spec Conformance", "input": "", "output": "Comparing Python Type Checkers: Typing Spec Conformance\nWhen you write typed Python, you expect your type checker to follow the rules of the language. But how closely do today's type checkers actually follow the Python typing specification?\n\nWe wrote a blog that explains what typing spec conformance means, how different type checkers compare, and what the conformance numbers don't tell you.\n\nRead the full blog here: https://pyrefly.org/blog/typing-conformance-comparison/\n\nA brief TLDR/editorializing from me, the author:\n\nSince there are several next-gen Python type checkers being developed right now (Pyrefly, Ty, Zuban), people are hungry for anything resembling a benchmark/objective comparison between them. Typing spec conformance is one such standard, but it has many limitations, which this blog attempts to clarify. Below is an early-March snapshot of the public conformance results. It will be out of date soon because most type checkers are being actively developed.\n\n| Type Checker | Fully Passing | Pass Rate | False Positives | False Negatives |\n|:------------:|:-------------:|:---------:|:---------------:|:---------------:|\n| pyright      | 136/139       | 97.8%     | 15              | 4               |\n| zuban        | 134/139       | 96.4%     | 10              | 0               |\n| pyrefly      | 122/139       | 87.8%     | 52              | 21              |\n| mypy         | 81/139        | 58.3%     | 231             | 76              |\n| ty           | 74/139        | 53.2%     | 159             | 211             |"}
{"instruction": "I built nitro-pandas — a pandas-compatible library powered by Polars. Same syntax, up to 10x faster.", "input": "", "output": "I built nitro-pandas — a pandas-compatible library powered by Polars. Same syntax, up to 10x faster.\nI got tired of rewriting all my pandas code to get Polars performance, so I built nitro-pandas — a drop-in wrapper that gives you the pandas API with Polars running under the hood.\n\n**What My Project Does**\n\nnitro-pandas is a pandas-compatible DataFrame library powered by Polars. Same syntax as pandas, but using Polars’ Rust engine under the hood for better performance. It supports lazy evaluation, full CSV/Parquet/JSON/Excel I/O, and automatically falls back to pandas for any method not yet natively implemented.\n\n**Target Audience**\n\nData scientists and engineers familiar with pandas who want better performance on large datasets without relearning a new API. It’s an early-stage project (v0.1.5), functional and available on PyPI, but still growing. Feedback and contributors are very welcome.\n\n**Comparison**\n\nvs pandas: same syntax, 5-10x faster on large datasets thanks to Polars backend. vs Polars: no need to learn a new API, just change your import. vs modin: modin parallelizes pandas internals — nitro-pandas uses Polars’ Rust engine which is fundamentally faster.\n\nGitHub: [https://github.com/Wassim17Labdi/nitro-pandas](https://github.com/Wassim17Labdi/nitro-pandas)\n\npip install nitro-pandas\n\nWould love to know what pandas methods you use most — it’ll help prioritize what to implement natively next!"}
{"instruction": "Why does it take 3 hours to read my own email with Python in 2026?", "input": "", "output": "Why does it take 3 hours to read my own email with Python in 2026?\n  Here is what Google thinks is a reasonable developer experience:\n\n  1. Create a Google Cloud project\n\n  2. Enable the Gmail API (but also the People API for contacts, and the Calendar API separately)\n\n  3. Configure an OAuth consent screen - answer 15 questions about your \"app\" when all you want is to read your own inbox\n\n  4. Create OAuth credentials - but wait, which type? Web? Desktop? Service account? The docs point you in circles\n\n  5. Download a credentials JSON file, put it somewhere your script can find it\n\n  6. Write the OAuth flow code - handle token refresh, token expiry, token storage\n\n  7. Run it, get a browser redirect, approve permissions on a consent screen that warns users YOUR OWN APP is \"unverified\"\n\n  8. Pray the token doesn't expire while you're still debugging step 6\n\n  And that's the HAPPY PATH. Half the tutorials are outdated, reference deprecated libraries, or skip critical steps. The official Google docs read like they were written by three different teams who never talked to each other.\n\nI've been building software for close to 40 years. I've shipped systems in healthcare, security, enterprise - real production environments. And I genuinel struggled with this. Not because the concepts are hard, but because the process is needlessly hostile to developers.\n\nThe real kicker: I also need my users to be able to connect their Gmail accounts. So \"just use a service account\" or \"just use an App Password\" doesn't cut it.\n\nI need actual OAuth that works for end users, which means going through Google's verification process, which is its own special circle of frustration.\n\n  All I want is a Python library where I can write something like:\n\n  gmail = connect\\_to\\_gmail()\n\n  emails = gmail.inbox(last=50)\n\n  contacts = gmail.contacts()\n\n  calendar = gmail.events(next\\_week=True)\n\nInstead I'm drowning in credential files, token pickle storage, scope strings, and consent screen configurations.\n\n  Has anyone found a genuinely good solution for this? A library or service that wraps the OAuth pain and just lets you work with Gmail/Contacts/Calendar data?\n\nSomething your users can set up without a 3-hour onboarding session?\n\n  I keep thinking someone must have solved this by now. Because right now, Google has effectively made it harder to programmatically access your own email than it was 20 years ago with IMAP."}
{"instruction": "What are some fun Python-heavy niches?", "input": "", "output": "What are some fun Python-heavy niches?\nI going to try making a Discord bot in py. Pygame and Raspberry Pi intrigue me as well\n\nCurious what other fun Py rabbit holes are out there that I don't know of!"}
{"instruction": "PyTogether, the 'Google Docs' for Python (free and open-source, real-time browser IDE)", "input": "", "output": "PyTogether, the 'Google Docs' for Python (free and open-source, real-time browser IDE)\nI shared this project here a while ago, but after adding a lot of new features and optimizations, I wanted to post an update. Over the past eight months, I’ve been building [PyTogether](https://pytogether.org) (pytogether.org). The platform has recently started picking up traction and just crossed 4,000 signups, which has been awesome to see.\n\n# What My Project Does\n\nIt is a real-time, collaborative Python IDE designed with beginners in mind (think Google Docs, but for Python). It’s meant for pair programming, tutoring, or just coding Python together. It’s completely free. No subscriptions, no ads, nothing. Just create an account (or feel fry to try the offline playground at [https://pytogether.org/playground](https://pytogether.org/playground), no account required), make a group, and start a project. Has proper code-linting, extremely intuitive UI, autosaving, drawing features (you can draw directly onto the IDE and scroll), live selections, and voice/live chats per project. There are no limitations at the moment (except for code size to prevent malicious payloads). There is also built-in support for libraries like matplotlib.\n\nYou can also share links for editing or read-only, exactly like Google Docs. For example: [https://pytogether.org/snippet/eyJwaWQiOjI1MiwidHlwZSI6InNuaXBwZXQifQ:1w15A5:24aIZlONamExTLQONAIC79cqcx3savn-\\_BC-Qf75SNY](https://pytogether.org/snippet/eyJwaWQiOjI1MiwidHlwZSI6InNuaXBwZXQifQ:1w15A5:24aIZlONamExTLQONAIC79cqcx3savn-_BC-Qf75SNY)\n\nSource code: [https://github.com/SJRiz/pytogether](https://github.com/SJRiz/pytogether)\n\n# Target Audience\n\nIt’s designed for tutors, educators, or Python beginners. Recently, I've also tried pivoting it towards the interviewing space.\n\n# Comparison With Existing Alternatives\n\nWhy build this when Replit or VS Code Live Share already exist?\n\nBecause my goal was simplicity and education. I wanted something lightweight for beginners who just want to write and share simple Python scripts (alone or with others), without downloads, paywalls, or extra noise. There’s also no AI/copilot built in, something many teachers and learners actually prefer. I also focused on a communication-first approach, where the IDE is the \"focus\" of communication (hence why I added tools like drawing, voice/live chats, etc).\n\n# Project Information\n\nTech stack (frontend):\n\n* React + TailwindCSS\n* CodeMirror for linting\n* Y.js for real-time syncing\n* Pyodide\n\nI use Pyodide (in a web worker) for Python execution directly in the browser, this means you can actually use advanced libraries like NumPy and Matplotlib while staying fully client-side and sandboxed for safety.\n\nI don’t enjoy frontend or UI design much, so I leaned on AI for some design help, but all the logic/code is mine. Deployed via Vercel.\n\nTech stack (backend):\n\n* Django (channels, auth, celery/redis support made it a great fit)\n* PostgreSQL via Supabase\n* JWT + OAuth authentication\n* Redis for channel layers + caching + queues for workers\n* Celery for background tasks/async processing\n\nFully Dockerized + deployed on a VPS (8GB RAM, $7/mo deal)\n\nData models:\n\nUsers <-> Groups -> Projects -> Code\n\nUsers can join many groups\n\nGroups can have multiple projects\n\nEach project belongs to one group and has one code file (kept simple for beginners, though I may add a file system later).\n\nMy biggest technical challenges were around performance and browser execution. One ma"}
{"instruction": "I built a desktop music player with Python because I was tired of bloated apps and compressed music", "input": "", "output": "I built a desktop music player with Python because I was tired of bloated apps and compressed music\nHey everyone,\n\nI've been working on a project called **BeatBoss** for a while now. Basically, I wanted a Hi-Res music player that felt modern but didn't eat up all my RAM like some of the big apps do.\n\nIt’s a desktop player built with **Python** and **Flet** (which is a wrapper for Flutter).\n\n# What My Project Does\n\nIt streams directly from DAB (publicly available Hi-Res music), manages offline downloads and has a cool feature for importing playlists. You can plug in a YouTube playlist, and it searches the DAB API for those songs to add them directly to your library in the app. It’s got synchronized lyrics, libraries, and a proper light and dark mode.\nAny other app which uses DAB on any other device will sync with these libraries.\n\n# Target Audience\n\nHonestly, anyone who listens to music on their PC, likes high definition music and wants something cleaner than Spotify but more modern than the old media players. Also might be interesting if you're a standard Python dev looking to see how Flet handles a more complex UI.\n\nIt's fully open source. Would love to hear what you think or if you find any bugs (v1.2 just went live).\n\n# Link\n\n[https://github.com/TheVolecitor/BeatBoss](https://github.com/TheVolecitor/BeatBoss)\n\n# Comparison\n\n|Feature|BeatBoss|Spotify / Web Apps|Traditional (VLC/Foobar)|\n|:-|:-|:-|:-|\n|**Audio Quality**|**Raw Uncompressed**|Compressed Stream|Uncompressed|\n|**Resource Usage**|**Low (Native)**|High (Electron/Web)|Very Low|\n|**Downloads**|**Yes (MP3 Export)**|Encrypted Cache Only|N/A|\n|**UI Experience**|**Modern / Fluid**|Modern|Dated / Complex|\n|**Lyrics**|**Synchronized**|Synchronized|Plugin Required|\n\n# Screenshots\n\n[https://ibb.co/3Yknqzc7](https://ibb.co/3Yknqzc7)\n[https://ibb.co/cKWPcH8D](https://ibb.co/cKWPcH8D)\n[https://ibb.co/0px1wkfz](https://ibb.co/0px1wkfz)"}
{"instruction": "Yoo... https://subprocess.run actually redirects to the Python docs for subprocess.run()", "input": "", "output": "Yoo... https://subprocess.run actually redirects to the Python docs for subprocess.run()\nApparently, subprocess.run is an actual domain, and it redirects to https://docs.python.org/3/library/subprocess.html#subprocess.run\n\nWas this some kind of Easter egg? I would like to officially claim that I found it first lol."}
{"instruction": "Which Python project made you realize how powerful the language is?", "input": "", "output": "Which Python project made you realize how powerful the language is?\nCould be anything — automation, a quick data script, a web app, or even a beginner-friendly tool — Python’s simplicity usually hits instantly.\n\nWhat was the project that made you appreciate Python’s magic?"}
{"instruction": "From Python 3.3 to today: ending 15 years of subprocess polling", "input": "", "output": "From Python 3.3 to today: ending 15 years of subprocess polling\nFor \\~15 years, Python's `subprocess.Popen.wait()` implemented timeouts using busy-loop polling. This post explains how that was finally replaced with true event-driven waiting on POSIX systems: `pidfd_open()` \\+ `poll()` on Linux and `kqueue()` on BSD / macOS. The result is zero polling and fewer context switches. The same improvement now landing both in psutil and CPython itself.\n\n[https://gmpy.dev/blog/2026/event-driven-process-waiting](https://gmpy.dev/blog/2026/event-driven-process-waiting)"}
{"instruction": "Choosing a Python Logging Library in 2026 (Comparison)", "input": "", "output": "Choosing a Python Logging Library in 2026 (Comparison)\nI just published [a comparison of Python logging libraries](https://www.dash0.com/guides/python-logging-libraries) for\n2026: stdlib, structlog, Loguru, and a couple of others that\nstill show up in search results (Logbook, picologging).\n\nThe short version: stdlib + python-json-logger is the safe\ndefault. structlog is faster (~2x in benchmarks) and has\nthe best OTel and framework integration story. Loguru is the\neasiest to set up but needs an extra indirection layer for\nOpenTelemetry.\n\nCurious what people here are actually using in production and\nwhether the OTel integration story (or lack of it) is actually influencing choices."}
{"instruction": "What are people using instead of Anaconda these days?", "input": "", "output": "What are people using instead of Anaconda these days?\nI’ve been using Anaconda/Conda for years, but I’m increasingly frustrated with the solver slowness. It feels outdated\n\nWhat are people actually using nowadays for Python environments and dependency management?\n\n* micromamba / mamba?\n* pyenv + venv + pip?\n* Poetry?\n* something else?\n\nI’m mostly interested in setups that:\n\n* don’t mess with system Python\n* are fast and predictable\n* stay compatible with common scientific / ML / pip packages\n* easy to manage for someone who's just messing around (I am a game dev, I use python on personal projects)\n\nCurious what the current “best practice” is in 2026 and what’s working well in real projects"}
{"instruction": "Pytorch Now Uses Pyrefly for Type Checking", "input": "", "output": "Pytorch Now Uses Pyrefly for Type Checking\nFrom the official Pytorch blog:\n\n> We’re excited to share that PyTorch now leverages Pyrefly to power type checking across our core repository, along with a number of projects in the PyTorch ecosystem: Helion, TorchTitan and Ignite. For a project the size of PyTorch, leveraging typing and type checking has long been essential for ensuring consistency and preventing common bugs that often go unnoticed in dynamic code.\n\n> Migrating to Pyrefly brings a much needed upgrade to these development workflows, with lightning-fast, standards-compliant type checking and a modern IDE experience. With Pyrefly, our maintainers and contributors can catch bugs earlier, benefit from consistent results between local and CI runs, and take advantage of advanced typing features. In this blog post, we’ll share why we made this transition and highlight the improvements PyTorch has already experienced since adopting Pyrefly.\n\nFull blog post: https://pytorch.org/blog/pyrefly-now-type-checks-pytorch/"}
{"instruction": "Python API Framework Benchmark: FastAPI vs Django vs Litestar - Real Database Workloads", "input": "", "output": "Python API Framework Benchmark: FastAPI vs Django vs Litestar - Real Database Workloads\nHey everyone,\n\nI benchmarked the major Python frameworks with **real PostgreSQL workloads**: complex queries, nested relationships, and properly optimized eager loading for each framework (select\\_related/prefetch\\_related for Django, selectinload for SQLAlchemy). Each framework tested with multiple servers (Uvicorn, Granian, Gunicorn) in isolated Docker containers with strict resource limits.\n\nAll database queries are optimized using each framework's best practices - this is a fair comparison of properly-written production code, not naive implementations.\n\n# Key Finding\n\n**Performance differences collapse from 20x (JSON) to 1.7x (paginated queries) to 1.3x (complex DB queries).** Database I/O is the great equalizer - framework choice barely matters for database-heavy apps.\n\n# Frameworks & Servers Tested\n\n* **Django Bolt** (runbolt server)\n* **FastAPI** (fastapi-uvicorn, fastapi-granian)\n* **Litestar** (litestar-uvicorn, litestar-granian)\n* **Django REST Framework** (drf-uvicorn, drf-granian, drf-gunicorn)\n* **Django Ninja** (ninja-uvicorn, ninja-granian)\n\nEach framework tested with multiple production servers: Uvicorn (ASGI), Granian (Rust-based ASGI/WSGI), and Gunicorn+gevent (async workers).\n\n# Test Setup\n\n* **Hardware:** MacBook M2 Pro, 32GB RAM\n* **Database:** PostgreSQL with realistic data (500 articles, 2000 comments, 100 tags, 50 authors)\n* **Docker Isolation:** Each framework runs in its own container with strict resource limits:\n   * 500MB RAM limit (`--memory=500m`)\n   * 1 CPU core limit (`--cpus=1`)\n   * Sequential execution (start → benchmark → stop → next framework)\n* **Load:** 100 concurrent connections, 10s duration, 3 runs (best taken)\n\nThis setup ensures completely fair comparison - no resource contention between frameworks, each gets identical isolated environment.\n\n# Endpoints Tested\n\n|Endpoint|Description|\n|:-|:-|\n|`/json-1k`|\\~1KB JSON response|\n|`/json-10k`|\\~10KB JSON response|\n|`/db`|10 database reads (simple query)|\n|`/articles?page=1&page_size=20`|Paginated articles with nested author + tags (20 per page)|\n|`/articles/1`|Single article with nested author + tags + comments|\n\n# Results\n\n# 1. Simple JSON (/json-1k) - Requests Per Second\n\n**20x performance difference** between fastest and slowest.\n\n|Framework|RPS|Latency (avg)|\n|:-|:-|:-|\n|litestar-uvicorn|**31,745**|0.00ms|\n|litestar-granian|22,523|0.00ms|\n|bolt|22,289|0.00ms|\n|fastapi-uvicorn|12,838|0.01ms|\n|fastapi-granian|8,695|0.01ms|\n|drf-gunicorn|4,271|0.02ms|\n|drf-granian|4,056|0.02ms|\n|ninja-granian|2,403|0.04ms|\n|ninja-uvicorn|2,267|0.04ms|\n|drf-uvicorn|1,582|0.06ms|\n\n# 2. Real Database - Paginated Articles (/articles?page=1&page_size=20)\n\n**Performance gap shrinks to just 1.7x** when hitting the database. Query optimization becomes the bottleneck.\n\n|Framework|RPS|Latency (avg)|\n|:-|:-|:-|\n|litestar-uvicorn|**253**|0.39ms|\n|litestar-granian|238|0.41ms|\n|bolt|237|0.42ms|\n|fastapi-uvicorn|225|0.44ms|\n|drf-granian|221|0.44ms|\n|fastapi-granian|218|0.45ms|\n|drf-uvicorn|178|0.54ms|\n|drf-gunicorn|146|0.66ms|\n|ninja-uvicorn|146|0.66ms|\n|ninja-granian|142|0.68ms|\n\n# 3. Real Database - Article Detail (/articles/1)\n\n**Gap narrows to 1.3x** \\- frameworks perform nearly identically on complex database queries.\n\nSingle article with all nested data (author + tags + comments):\n\n|Framework|RPS|Latency (avg)|\n|:-|:-|:-|\n|fastapi-uvicorn|**550**|0.18ms|\n|litestar-granian|543|0.18ms|\n|li"}
{"instruction": "An announcement from the Steering Council regarding the JIT project", "input": "", "output": "An announcement from the Steering Council regarding the JIT project\n> the Steering Council is formally requesting a Standards Track PEP be authored that the community can discuss and the Steering Council can formally accept (or reject), making the case for the JIT as a supported, non-experimental part of CPython\n\nhttps://discuss.python.org/t/an-announcement-from-the-steering-council-regarding-the-jit-project/107638"}
{"instruction": "Title: Kreuzberg v4.5: We loved Docling's model so much that we gave it a faster engine", "input": "", "output": "Title: Kreuzberg v4.5: We loved Docling's model so much that we gave it a faster engine\nHi folks,\n\nWe just released [Kreuzberg v4.5](https://github.com/kreuzberg-dev/kreuzberg), and it's a big one.\n\nKreuzberg is an open-source (MIT) document intelligence framework supporting 12 programming languages. Written in Rust, with native bindings for Python, TypeScript/Node.js, PHP, Ruby, Java, C#, Go, Elixir, R, C, and WASM. It extracts text, structure, and metadata from 88+ formats, runs OCR, generates embeddings, and is built for AI pipelines and document processing at scale.\n\n## What's new in v4.5\n\nA lot! For the full release notes, please visit our [changelog](https://github.com/kreuzberg-dev/kreuzberg/releases).\n\nThe core is this: Kreuzberg now understands document structure (layout/tables), not just text. You'll see that we used Docling's model to do it.\n\nDocling is a great project, and their layout model, RT-DETR v2 (Docling Heron), is excellent. It's also fully open source under a permissive Apache license. We integrated it directly into Kreuzberg, and we want to be upfront about that.\n\nWhat we've done is embed it into a Rust-native pipeline. The result is document layout extraction that matches Docling's quality and, in some cases, outperforms it. It's 2.8x faster on average, with a fraction of the memory overhead, and without Python as a dependency. If you're already using Docling and happy with the quality, give Kreuzberg a try.\n\nWe benchmarked against Docling on 171 PDF documents spanning academic papers, government and legal docs, invoices, OCR scans, and edge cases:\n\n- Structure F1: Kreuzberg 42.1% vs Docling 41.7%\n- Text F1: Kreuzberg 88.9% vs Docling 86.7%\n- Average processing time: Kreuzberg 1,032 ms/doc vs Docling 2,894 ms/doc\n\nThe speed difference comes from Rust's native memory management, pdfium text extraction at the character level, ONNX Runtime inference, and Rayon parallelism across pages.\n\nRT-DETR v2 (Docling Heron) classifies 17 document element types across all 12 language bindings. For pages containing tables, Kreuzberg crops each detected table region from the page image and runs TATR (Table Transformer), a model that predicts the internal structure of tables (rows, columns, headers, and spanning cells). The predicted cell grid is then matched against native PDF text positions to reconstruct accurate markdown tables.\n\nKreuzberg extracts text directly from the PDF's native text layer using pdfium, preserving exact character positions, font metadata (bold, italic, size), and unicode encoding. Layout detection then classifies and organizes this text according to the document's visual structure. For pages without a native text layer, Kreuzberg automatically detects this and falls back to Tesseract OCR.\n\nWhen a PDF contains a tagged structure tree (common in PDF/A and accessibility-compliant documents), Kreuzberg uses the author's original paragraph boundaries and heading hierarchy, then applies layout model predictions as classification overrides.\n\nPDFs with broken font CMap tables (\"co mputer\" → \"computer\") are now fixed automatically — selective page-level respacing detects affected pages and applies per-character gap analysis, reducing garbled lines from 406 to 0 on test documents with zero performance impact. There's also a new multi-backend OCR pipeline with quality-based fallback, PaddleOCR v2 with a unified 18,000+ character multilingual model, and extraction result caching for all file types.\n\nIf you're running"}
{"instruction": "Tip: use msgspec for JSON decoding — it decodes straight into your type at C speed", "input": "", "output": "Tip: use msgspec for JSON decoding — it decodes straight into your type at C speed\nA tip that's saved us a lot of boilerplate across our Python stack (Litestar, and our document-extraction tooling): stop decoding JSON into `dict[str, Any]` and casting/`.get()`-ing your way through it. Decode straight into your declared type.\n\n`msgspec` validates and decodes directly into your type at C speed. Quick comparison of the usual options on the same payload:\n\n- `json.loads` / `orjson.loads` -> `dict[str, Any]` (cast and pray; orjson just faster)\n- `pydantic` TypeAdapter(...).validate_json -> your model, validated + rich, but heavier\n- `msgspec.json.decode(raw, type=T)` -> your type, validated, C-fast\n\npydantic does far more and its Rust core is fast; for model-heavy code it's still my default. But on hot paths where you just need decode-into-a-struct, a C decoder going straight to the type is hard to beat.\n\nWith PEP 695 generics the whole (de)serialization layer collapses to one function:\n\n```python\ndef deserialize[T](raw: bytes, t: type[T]) -> T:\n    return msgspec.json.decode(raw, type=t, strict=False)\n\ndeserialize(raw, Grant)        # -> Grant\ndeserialize(raw, list[Grant])  # -> list[Grant]\n```\n\nWe landed on this while building Litestar (msgspec is a big reason it's fast) and reuse it across everything now. How do you handle hot-path decoding — msgspec, orjson + manual validation, or full pydantic?"}
{"instruction": "Discover when a feature was added to Python", "input": "", "output": "Discover when a feature was added to Python\nI made a tool to discover when a feature was added to Python.\n\nIt's [online here](https://www.pythonmorsels.com/since/) and on PyPI as [sincewhen](https://pypi.org/project/sincewhen/).\n\nYou can look up a feature **by name** or **paste code** to look up all the features within it (that only works for code written using modern Python syntax).\n\nThat page shows [some example feature story arcs](https://www.pythonmorsels.com/since/#stories-heading) that can be discovered with this.\n\nI made this primarily as **a teaching tool** so I can better answer questions from my Python-learning students with a bit more historical context.\n\n**Note**: I feel this qualifies more as a \"resource\" than a \"showcase\". I'm embracing EAFP over LBYL and hoping for the best. Call me out of I'm wrong here."}
{"instruction": "Robyn (finally) supports Python 3.14 🎉", "input": "", "output": "Robyn (finally) supports Python 3.14 🎉\nFor the unaware - [Robyn](https://github.com/sparckles/Robyn) is a fast, async Python web framework built on a Rust runtime.\n\nPython 3.14 support has been pending for a while.\n\nWanted to share it with folks outside the Robyn community.\n\nYou can check out the release at - [https://github.com/sparckles/Robyn/releases/tag/v0.74.0](https://github.com/sparckles/Robyn/releases/tag/v0.74.0)"}
{"instruction": "`safer`: a tiny utility to avoid partial writes to files and streams", "input": "", "output": "`safer`: a tiny utility to avoid partial writes to files and streams\n**What My Project Does**\n\nIn 2020, I broke a few configuration files, so I wrote something to help prevent breaking a lot the next time, and turned it into a little library: https://github.com/rec/safer\n\nIt's a drop-in replacement for `open` that only writes the file when everything has completed successfully, like this:\n\n    with safer.open(filename, 'w') as fp:\n        fp.write('oops')\n        raise ValueError\n     # File is untouched\n\nBy default, the data is cached in memory, but for large files, there's a flag to allow you to cache it as a file that is renamed when the operation is complete.\n\nYou can also use it for file sockets and other streams:\n\n    try:\n        with safer.writer(socket.send) as send:\n              send_bytes_to_socket(send)\n    except Exception:\n         # Nothing has been sent\n         send_error_message_to_socket(socket.send)\n\n**Target Audience**\n\nThis is a mature, production-quality library for any application where partial writes are possible. There is extensive testing and it handles some obscure edge cases.\n\nIt's tested on Linux, MacOS and Windows and has been stable and essentially unchanged for years.\n\n**Comparison**\n\nThere doesn't seem to be another utility preventing partial writes. There are multiple atomic file writers which solve a different problem, the best being this: https://github.com/untitaker/python-atomicwrites\n\n**Note**\n\n\\#noAI was used in the writing or maintenance of this program."}
{"instruction": "Title: I built WSE — Rust-accelerated WebSocket engine for Python (2M msg/s, E2E encrypted)", "input": "", "output": "Title: I built WSE — Rust-accelerated WebSocket engine for Python (2M msg/s, E2E encrypted)\n  I've been doing real-time backends for a while — trading, encrypted messaging between services, that kind of stuff. Web sockets in python are painfully slow once you need actual throughput. tried the usual — pure python libs cap at maybe 10k  msg/s, then you're looking at rewriting in go or running some separate server and gluing it together with redis.\n\n  so i built wse. it's a websocket engine that sits inside fastapi. you write python, the transport runs in rust (pyo3). tcp accept, framing, compression, encryption, ping/pong — all rust. python never sees raw frames.\n\n  What My Project Does\n\n  the fast part comes from two things:\n\n  jwt validation happens in rust during the ws handshake. cookie parsing, hs256 sig check, expiry — done before python knows someone connected. 0.5ms instead of 23ms. python just gets the user\\_id.\n\n  then there's drain mode. rust queues up incoming messages, python grabs them in batches. one gil acquire per batch, not per message. same on the way out — write coalescing, up to 64 messages flushed in one syscall.\n\n  from wse\\_server import create\\_wse\\_router, WSEConfig\n\n  config = WSEConfig(\n\njwt\\_secret=\"your-secret\",\n\ncompression=True,\n\nencryption=True,\n\n  )\n\n  app.include\\_router(create\\_wse\\_router(config))\n\n  2M msg/s on epyc, 130k+ on a macbook. e2e encryption (ecdh p-256 + aes-gcm-256), zlib, msgpack, pub/sub, dedup, circuit breaker, rate limiting.\n\n  has ts/react and python clients:\n\n  from wse\\_client import connect\n\n  async with connect(\"ws://localhost:5006/wse\", token=\"jwt...\") as client:\n\nawait client.subscribe(\\[\"notifications\"\\])\n\nasync for event in client:\n\nprint(event.type, event.payload)\n\n  376+ tests across the whole thing — pytest for server and python client, vitest for ts client. ci runs on python 3.12-3.14, binary wheels on pypi.\n\n  Target Audience\n\n  if you have a python backend pushing real-time data and you're hitting the wall with pure python websockets but don't want to maintain a separate go/rust service — this is for that. i run it in production for trading (latency matters) and\n\n  encrypted service-to-service messaging.\n\n  Comparison\n\n  most python ws libs are pure python so you're bottlenecked by the interpreter on framing and serialization. the typical solution is to stick a go/rust server in front and talk to it over ipc or redis — works but now you have two services,\n\n  two deploys, serialization overhead in between. wse just runs rust inside your python process via pyo3. one process, one deploy, business logic stays in python.\n\n  [https://github.com/silvermpx/wse](https://github.com/silvermpx/wse)\n\n  pip install wse-server / pip install wse-client / npm install wse-client"}
{"instruction": "i built a Python library that tells you who said what in any audio file", "input": "", "output": "i built a Python library that tells you who said what in any audio file\n# What My Project Does\n\n**voicetag** is a Python library that identifies speakers in audio files and transcribes what each person said. You enroll speakers with a few seconds of their voice, then point it at any recording — it figures out who's talking, when, and what they said.\n\n    from voicetag import VoiceTag\n\n    vt = VoiceTag()\n    vt.enroll(\"Christie\", [\"christie1.flac\", \"christie2.flac\"])\n    vt.enroll(\"Mark\", [\"mark1.flac\", \"mark2.flac\"])\n\n    transcript = vt.transcribe(\"audiobook.flac\", provider=\"whisper\")\n\n    for seg in transcript.segments:\n        print(f\"[{seg.speaker}] {seg.text}\")\n\nOutput:\n\n    [Christie] Gentlemen, he sat in a hoarse voice. Give me your\n    [Christie] word of honor that this horrible secret shall remain buried amongst ourselves.\n    [Christie] The two men drew back.\n\nUnder the hood it combines pyannote.audio for diarization with resemblyzer for speaker embeddings. Transcription supports 5 backends: local Whisper, OpenAI, Groq, Deepgram, and Fireworks — you just pick one.\n\nIt also ships with a CLI:\n\n    voicetag enroll \"Christie\" sample1.flac sample2.flac\n    voicetag transcribe recording.flac --provider whisper --language en\n\nEverything is typed with Pydantic v2 models, results are serializable, and it works with any spoken language since matching is based on voice embeddings not speech content.\n\nSource code: [https://github.com/Gr122lyBr/voicetag](https://github.com/Gr122lyBr/voicetag) Install: `pip install voicetag`\n\n# Target Audience\n\nAnyone working with audio recordings who needs to know who said what — podcasters, journalists, researchers, developers building meeting tools, legal/court transcription, call center analytics. It's production-ready with 97 tests, CI/CD, type hints everywhere, and proper error handling.\n\nI built it because I kept dealing with recorded meetings and interviews where existing tools would give me either \"SPEAKER\\_00 / SPEAKER\\_01\" labels with no names, or transcription with no speaker attribution. I wanted both in one call.\n\n# Comparison\n\n* **pyannote.audio alone**: Great diarization but only gives anonymous speaker labels (SPEAKER\\_00, SPEAKER\\_01). No name matching, no transcription. You have to build the rest yourself. voicetag wraps pyannote and adds named identification + transcription on top.\n* **WhisperX**: Does diarization + transcription but no named speaker identification. You still get anonymous labels. Also no enrollment/profile system.\n* **Manual pipeline** (wiring pyannote + resemblyzer + whisper yourself): Works but it's \\~100 lines of boilerplate every time. voicetag is 3 lines. It also handles parallel processing, overlap detection, and profile persistence.\n* **Cloud services** (Deepgram, AssemblyAI): They do speaker diarization but with anonymous labels. voicetag lets you enroll known speakers so you get actual names. Plus it runs locally if you want — no audio leaves your machine."}
{"instruction": "Termgotchi – Terminal pet that mirrors your server health", "input": "", "output": "Termgotchi – Terminal pet that mirrors your server health\nWhat it does\nA Tamagotchi living in your terminal. Server CPU spikes → pet gets stressed. High memory usage → pet gets hungry. Low disk space → pet gets sick. Pure Python, no dependencies.\n\nSource: https://github.com/pfurpass/Termgotchi\n\nTarget Audience\nToy project for terminal-dwelling developers and sysadmins. Not production monitoring — just fun.\n\nComparison\nGrafana and Netdata show graphs. Termgotchi shows a suffering pixel creature. No other terminal pet project ties pet state to live server metrics."}
{"instruction": "SQLite in Production: Why WAL Mode, busy_timeout, and 1-Writer Pools", "input": "", "output": "SQLite in Production: Why WAL Mode, busy_timeout, and 1-Writer Pools\nEvery time SQLite is brought up for production Python backends (FastAPI, Flask, Litestar), the common consensus is: *\"SQLite doesn't support concurrency. The moment two people hit your API, you'll get database is locked.\"*\n\nThis reputation is understandable, but it's based on SQLite's **default configuration**, which was designed decades ago for low-resource embedded devices, not web servers.\n\nWhen SQLite is tuned with modern PRAGMAs and a proper connection architecture, it can comfortably handle thousands of requests/sec with microsecond read latencies on a cheap VPS—completely bypassing the network latency of Postgres/MySQL.\n\nHere is the exact architectural blueprint for running SQLite under high concurrency in Python.\n\n---\n\n### 1. The Core Bottleneck: `DELETE` vs `WAL` Mode\n\nBy default, SQLite uses Rollback Journal mode (`journal_mode = DELETE`). In this mode:\n- Writing locks the entire database.\n- **Readers block writers, and writers block readers.**\n\nTo fix this, you must enable **WAL (Write-Ahead Logging)**:\n```python\nconn.execute(\"PRAGMA journal_mode = WAL;\")\n```\nIn WAL mode:\n- Changes are appended to a separate `.db-wal` file.\n- **Readers never block writers, and writers never block readers.**\n- You can have 50 concurrent async read queries executing simultaneously while a background worker writes new rows.\n\n---\n\n### 2. Eliminating `database is locked` (`busy_timeout`)\n\nEven in WAL mode, SQLite allows only **one active writer at a time**. If two threads or coroutines attempt to commit a write at the exact same millisecond, SQLite immediately throws:\n`sqlite3.OperationalError: database is locked`.\n\nWhy? Because the default `busy_timeout` is **0 milliseconds**! It fails instantly without retrying.\n\nFix it by giving SQLite a retry window:\n```python\nconn.execute(\"PRAGMA busy_timeout = 5000;\") # Wait up to 5000ms before erroring\n```\nUnder this setting, if connection A is writing, connection B will sleep and automatically retry for up to 5 seconds. In real-world workloads, writes take 0.2ms–2ms, so connection B succeeds imperceptibly.\n\n---\n\n### 3. Production PRAGMAs Checklist\n\nHere is the battle-tested configuration to apply on every newly opened connection:\n\n```python\nimport sqlite3\n\ndef get_db_connection(db_path: str = \"app.db\") -> sqlite3.Connection:\n    conn = sqlite3.connect(\n        db_path,\n        timeout=5.0, # Python-level timeout\n        check_same_thread=False\n    )\n    conn.row_factory = sqlite3.Row\n\n    # 1. Enable WAL mode\n    conn.execute(\"PRAGMA journal_mode = WAL;\")\n\n    # 2. Crash-safe in WAL mode, but skips excessive OS fsync() calls\n    conn.execute(\"PRAGMA synchronous = NORMAL;\")\n\n    # 3. Cache size (negative number = kibibytes; -64000 = ~64MB cache)\n    conn.execute(\"PRAGMA cache_size = -64000;\")\n\n    # 4. Memory-mapped I/O (reads bypass kernel copy buffers)\n    conn.execute(\"PRAGMA mmap_size = 268435456;\") # 256MB\n\n    # 5. Enforce foreign keys (disabled by default in SQLite!)\n    conn.execute(\"PRAGMA foreign_keys = ON;\")\n\n    # 6. Keep temp tables in RAM instead of disk\n    conn.execute(\"PRAGMA temp_store = MEMORY;\")\n\n    return conn\n```\n\n---\n\n### 4. The Python Architecture Rule: 1 Writer, N Readers\n\nIf you run multiple Gunicorn/Uvicorn workers, having all workers write directly to SQLite will eventually cause checkpoint starvation.\n\nThe cleanest architecture:\n1. **Readers:** Shared connection pool (e.g. `aiosqli"}
{"instruction": "Must the Python Software Foundation move out of the USA?", "input": "", "output": "Must the Python Software Foundation move out of the USA?\nThe Python Software Foundation (PSF) is the owner of the copyrights for Python and its trademarks. The PSF runs the largest Python conference in the world, #PyConUS. Python is one of the most important programming languages, used by developers and non-developers across the globe. Python and its community stand for openness, diversity, and support for underrepresented groups; the PSF funds a wide range of Python activities across many sub-communities worldwide.\n\nThe values that Python and its communities stand for are under heavy pressure due to the legal status of the Python Software Foundation as a corporation in the United States. The USA has, meanwhile, turned into a fascist regime, with entities like ICE acting in ways that we have seen in Nazi Germany between 1933 and 1945. The current U.S. regime is violently acting against migrants, underrepresented groups, queer people, etc.—the list is long and very well documented. ICE acts as a paramilitary entity that killed already several people - or should it be named \"murdered several people\"?\n\nShould the Python Software Foundation remain in the USA, or should the community pressure the PSF Board to take action and move the PSF as a legal entity out of the United States into a safer region like Canada or the European Union?"}
{"instruction": "When's the last time you saw Python 2 Super() syntax?", "input": "", "output": "When's the last time you saw Python 2 Super() syntax?\nI saw one yesterday during an interview and it really confused me at first since the feature has been deprecated for so long.\n\n\nAre there still code bases out there running Python 2? I used Python 3.8 at my last job and that made me feel like a dinosaur."}
{"instruction": "[P] I rebuilt PyRadiomics in PyTorch to make it 25× faster — here's what it took", "input": "", "output": "[P] I rebuilt PyRadiomics in PyTorch to make it 25× faster — here's what it took\nPyRadiomics 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.\n\nI 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.\n\nResults on an RTX 4070 Ti:\n\n  0.116s per scan vs 2.90s → 25× end-to-end speedup\n\n  No GPU? CPU-only mode is still 2.6× faster than PyRadiomics on 32 threads\n\n  Works on Apple Silicon too (3.56× faster than PyRadiomics 32-thread)\n\nThe 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⁻¹¹.\n\nIt's a drop-in replacement — same feature names and output format as PyRadiomics:\n\n  from fastrad import RadiomicsFeatureExtractor\n\n  extractor = RadiomicsFeatureExtractor(device=\"auto\")\n\n  features = extractor.execute(image\\_path, mask\\_path)\n\npip install fastrad\n\nGitHub: [github.com/helloerikaaa/fastrad](http://github.com/helloerikaaa/fastrad)\n\nPre-print: [https://papers.ssrn.com/sol3/papers.cfm?abstract\\_id=6436486](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=6436486)\n\nLicense: Apache 2.0\n\nHappy 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."}
{"instruction": "copier-astral: Modern Python project scaffolding with the entire Astral ecosystem", "input": "", "output": "copier-astral: Modern Python project scaffolding with the entire Astral ecosystem\nHey [r/Python](https://www.reddit.com/r/Python/)!\n\nI'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](https://github.com/ritwiktiwari/copier-astral) — a Copier template that gives you a production-ready Python project in seconds.\n\n# What My Project Does\n\nScaffolds a complete Python project with modern tooling pre-configured:\n\n* uv for package management (10-100x faster than pip)\n* ruff for linting + formatting (replaces black, isort, flake8)\n* ty for type checking (Astral's new Rust-based type checker)\n* pytest + hatch for testing (including multi-version matrix)\n* MkDocs with Material theme + mkdocstrings\n* pre-commit hooks\n* GitHub Actions CI/CD\n* Docker support\n* Typer CLI scaffold (optional)\n* git-cliff for auto-generated changelogs\n* License selection — choose from MIT, Apache 2.0, GPL, etc. during setup\n\n# Target Audience\n\nPython developers who want a modern, opinionated starting point for new projects. Good for:\n\n* Side projects where you don't want to spend an hour on setup\n* Production code that needs proper CI/CD, testing, and docs from day one\n* Anyone who's already bought into the Astral ecosystem and wants it all wired up\n\n# Comparison\n\nThe main difference: this uses Copier (which supports template updates) and goes all-in on Astral's toolchain including ty for type checking with optional Typer CLI scaffold if you're building a command-line tool and git-cliff for changelog generation from conventional commits.\n\n# Quick start:\n\n    pip install copier copier-template-extensions\n    copier copy --trust gh:ritwiktiwari/copier-astral my-project\n\n# Links:\n\n* **Template**: [https://github.com/ritwiktiwari/copier-astral](https://github.com/ritwiktiwari/copier-astral)\n* **Docs**: [https://ritwiktiwari.github.io/copier-astral/](https://ritwiktiwari.github.io/copier-astral/)\n* **Example generated project**: [https://github.com/ritwiktiwari/copier-astral-example](https://github.com/ritwiktiwari/copier-astral-example)\n* **Example generated docs**: [https://ritwiktiwari.github.io/copier-astral-example/](https://ritwiktiwari.github.io/copier-astral-example/)\n\n# Try it out!\n\nWould 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."}
{"instruction": "Which non-AI package from the last ~3 years completely changed how you write Python?", "input": "", "output": "Which non-AI package from the last ~3 years completely changed how you write Python?\nSometimes I think back to the times when I started using Python in 2018 and how much the language was changing in my first years. From Flask to FastAPI, Pydantic, Streamlit, Polars and Httpx. It was honestly fun to start new projects and explore all these developments and what they allowed you to do. Use it in your new project and surprise yourself with how much faster you can get things done, all while writing much cleaner code.\n\nCurrently I'm feeling most of the package I see are about AI; frameworks, LLM tooling, RAG, vector databases. Great developments, but they don't change the way I am working with the Language.\n\nIt sure has something to do with the fact that in the beginning when you start using a language you explore more and develop faster, and a lot of fundamental things were changing around that time (typing, async). But I keep wondering; am I missing out on packages that have changed the way you've used Python? Cause maybe I'm simply not looking in the right place. I'm thinking for example on how frontend frameworks handle state with signals.\n\nSo, two honest questions:\n\n1. Which package from the last ~3 years really changed how you use/write Python? (Uv and Ruff count)\n2. Did the pace of these foundational packages actually slow down, or am I just not in the right information streams?"}
{"instruction": "Google just open-sourced cel-expr-python (CEL) — safe, typed expressions for Python (C++ wrapper)", "input": "", "output": "Google just open-sourced cel-expr-python (CEL) — safe, typed expressions for Python (C++ wrapper)\nGoogle 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.\n\nRepo: https://github.com/cel-expr/cel-python\n\nAnnouncement: https://opensource.googleblog.com/2026/03/announcing-cel-expr-python-the-common-expression-language-in-python-now-open-source.html\n\nCodelab: https://github.com/cel-expr/cel-python/blob/main/codelab/index.lab.md\n\nWhy I’m interested:\n\n\\- It’s the official CEL team’s Python wrapper over the production CEL C++ implementation (so semantics should match what other CEL runtimes do).\n\n\\- 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).\n\n\\- It supports extensions and can serialize compiled expressions.\n\nQuick start (from the blog/docs; blog snippet had a small typo so I’m writing the corrected version here):\n\npip install cel-expr-python\n\nfrom cel\\_expr\\_python import cel\n\nenv = cel.NewEnv(variables={\"who\": cel.Type.STRING})\n\nexpr = env.compile(\"'Hello, ' + who + '!'\")\n\nprint(expr.eval(data={\"who\": \"World\"}).value())  # Hello, World!\n\nDoc snippet: serialize + reuse compiled expressions\n\nenv = cel.NewEnv(variables={\"x\": cel.Type.INT, \"y\": cel.Type.INT})\n\nexpr = env.compile(\"x + y > 10\")\n\nblob = expr.serialize()\n\nexpr2 = env.deserialize(blob)\n\nprint(expr2.eval(data={\"x\": 7, \"y\": 4}).value())  # True\n\nDoc snippet: custom function extension in Python\n\ndef my\\_func\\_impl(x):\n\nreturn x + 1\n\nmy\\_ext = cel.CelExtension(\n\n\"my\\_extension\",\n\n\\[\n\ncel.FunctionDecl(\n\n\"my\\_func\",\n\n\\[\n\ncel.Overload(\n\n\"my\\_func\\_int\",\n\ncel.Type.INT,\n\n\\[cel.Type.INT\\],\n\nimpl=my\\_func\\_impl,\n\n)\n\n\\],\n\n)\n\n\\],\n\n)\n\nenv = cel.NewEnv(extensions=\\[my\\_ext\\])\n\nexpr = env.compile(\"my\\_func(41)\")\n\nprint(expr.eval().value())  # 42\n\nSide note / parallel that made me click on this:\n\nI was just reading the r/Python thread on PEP 827 (type manipulation + expanding the type expression grammar):\n\nhttps://www.reddit.com/r/Python/comments/1rimuu7/pep\\_827\\_type\\_manipulation\\_has\\_just\\_been\\_published/\n\nThat whole “more expressive typed mini-languages inside Python” discussion got me thinking about the runtime side too: when you need user-authored rules/policies, it can be better to use a constrained, type-checkable expression language than to keep stretching Python itself (or to rely on ad-hoc AST eval).\n\nQuestions if there are any folks who’ve used CEL before:\n\n\\- Where has CEL worked well (policy engines, validation, feature flags, filtering, etc.)?\n\n\\- How does this compare to rolling your own AST-based evaluator / JsonLogic / JMESPath for real-world apps?\n\n\\- Any gotchas with Python integration, perf, or packaging (looks like Linux + py3.11+ right now)?"}
{"instruction": "PyTorch Lightning 2.6.2/2.6.3 supply chain attack malware executes on import, steals cloud creds.", "input": "", "output": "PyTorch Lightning 2.6.2/2.6.3 supply chain attack  malware executes on import, steals cloud creds.\nPSA for anyone running AI/ML training pipelines: PyTorch Lightning versions 2.6.2 and 2.6.3 (published April 30, 2026) were compromised in a supply chain attack. If you installed either version, your environment should be treated as fully compromised.\n\nTechnical details worth discussing:\n\nThe attack is import-time: modified \\_\\_init\\_\\_.py spawns a background thread the moment you run \"import lightning\". Downloads Bun JS runtime, deploys an 11MB obfuscated payload (router\\_runtime.js), harvests SSH keys, shell history, cloud credentials, GitHub/npm tokens, and crypto wallets. Exfiltrates via 4 parallel channels on port 443.\n\nThe worm component is what makes this particularly nasty: if it finds npm publish credentials, it injects into every package that token can publish and re-releases with a bumped patch version. The infection propagates downstream automatically.\n\nAttribution points to TeamPCP — the same group behind the Bitwarden CLI supply chain worm earlier this month. If anyone is tracking this campaign, they've now hit LiteLLM (March), Telnyx (March), Bitwarden CLI (April 22), and now PyTorch Lightning (April 30).\n\nI previously covered the Shai-Hulud worm's npm attack here if you want more background on the campaign architecture: [https://www.techgines.com/post/bitwarden-cli-supply-chain-attack-shai-hulud-npm-cicd](https://www.techgines.com/post/bitwarden-cli-supply-chain-attack-shai-hulud-npm-cicd)\n\nQuestions for the community:\n1. For those running locked dependency manifests — did your lock files protect you, or was the poisoned build pulled before lockfile hashes were checked?\n2. How are teams handling secret rotation in CI/CD environments where runners are ephemeral? Is rotating the credentials enough, or do you need to treat the base images as tainted?\n3. Any thoughts on the TeamPCP escalation pattern — deliberately targeting AI/ML infrastructure seems intentional. Cloud training credentials are uniquely valuable (access to GPU quota, large storage, model registries). Is this the new frontier for supply chain attacks?\n\nSafe version: 2.6.1. Full IOC list and attack chain at TechGines: [https://www.techgines.com/post/pytorch-lightning-supply-chain-attack-pypi-teamPCP](https://www.techgines.com/post/pytorch-lightning-supply-chain-attack-pypi-teamPCP)"}
{"instruction": "Python 3.15.0 candidate 2 is here!", "input": "", "output": "Python 3.15.0 candidate 2 is here!\nReported on https://blog.python.org/2026/09/python-3150-rc2/\n\n> It’s the final 3.15 release candidate!\n\n> https://www.python.org/downloads/release/python-3150rc2/\n\n> This is a candidate preview of Python 3.15\n\n> This release, 3.15.0rc2, is the final planned release candidate, containing around 144 bugfixes, build improvements and documentation changes from 76 contributors since 3.15.0rc1. Entering the release candidate phase, only reviewed code changes which are clear bug fixes are allowed between this release candidate and the final release.\n\n> The next release of Python 3.15 will be 3.15.0 final, scheduled for 2026-10-01.\n\n[Blog post continues](https://blog.python.org/2026/09/python-3150-rc2/)"}
{"instruction": "pip 26.0 - pre-release and upload-time filtering", "input": "", "output": "pip 26.0 - pre-release and upload-time filtering\nLike with pip 25.3, I had the honor of being the release manager for pip 26.0, the three big new features are:\n\n* `--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:`\n* `--uploaded-prior-to <timstamp>`, allowing you to restrict package upload time, e.g. `--uploaded-prior-to \"2026-01-01T00:00:00Z\"`\n* `--requirements-from-script <script>`, which will install dependencies declared in a script’s inline metadata ([PEP 723](https://peps.python.org/pep-0723/))\n\nRichard, 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/](https://ichard26.github.io/blog/2026/01/whats-new-in-pip-26.0/)\n\nThe official announcement is here: [https://discuss.python.org/t/announcement-pip-26-0-release/105947](https://discuss.python.org/t/announcement-pip-26-0-release/105947)\n\nAnd the full change log is here: [https://pip.pypa.io/en/stable/news/#v26-0](https://pip.pypa.io/en/stable/news/#v26-0)"}
{"instruction": "LogXide - Rust-powered logging for Python, 12.5x faster than stdlib (FileHandler benchmark)", "input": "", "output": "LogXide - Rust-powered logging for Python, 12.5x faster than stdlib (FileHandler benchmark)\nHi r/Python!\n\nI 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.\n\n### What My Project Does\nLogXide 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\\`.\n\n### Target Audience\nIt 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.\n\n### Comparison\nUnlike **Picologging** (written in C) or **Structlog** (pure Python), LogXide leverages Rust's memory safety and multi-threading primitives (like \\`crossbeam\\` channels and \\`BufWriter\\`).\n\nAgainst other libraries (real file I/O with formatting benchmarks):\n- **12.5x faster** than the Python \\`stdlib\\` (2.09M msgs/sec vs 167K msgs/sec)\n- **25% faster** than \\`Picologging\\`\n- **2.4x faster** than \\`Structlog\\`\n\n*Note: It is NOT a 100% drop-in replacement. It does not support custom Python \\`logging.Handler\\` subclasses, and \\`Logger\\`/\\`LogRecord\\` cannot be subclassed.*\n\n### Quick Start\n\n\\`\\`\\`python\nfrom logxide import logging\n\nlogging.basicConfig(level=logging.INFO,\n    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\nlogger = logging.getLogger('myapp')\nlogger.info('Hello from LogXide!')\n\\`\\`\\`\n\n### Links\n\n- **GitHub**: https://github.com/Indosaram/logxide\n- **Docs**: https://indosaram.github.io/logxide/\n- **PyPI**: \\`pip install logxide\\`\n\nHappy to answer any questions!"}
{"instruction": "I made a fast, structured PDF extractor for Python; 300 pages a second", "input": "", "output": "I made a fast, structured PDF extractor for Python; 300 pages a second\n**reposting because i've made significant changes and improvements; figured it's worth sharing the updated version. the post was vague and the quality and speed were much worse.**\n\n## what my project does\n\na fast PDF extractor for Python (bindings), written in C using MuPDF. outputs structured JSON with full layout metadata: geometry, typography, tables, and document structure. i took many of pymupdf4llm's heuristics and approach but rewrote it in C for speed, then bound it to Python so it's easy to use.\n\n**speed:** ~300 pages/second on a Ryzen 4800H, (4 cores @ use). no GPU needed.\n\n- 1 million pages in ~55 minutes.\n- tested on a ~1600 page table- and text-heavy document. performance varies with core count and layout density; ~300 pps is a conservative average.\n\n## the problem\n\nmost PDF extractors give you either raw text (fast but unusable) or over-engineered solutions (slow, opinionated). this gives structured data you can control; for building smarter chunks based on document layout, not just word count. and it's fast, especially when processing large volumes.\n\n**paddle, deepseek-ocr, marker, docling, etc are viable for most cases. though, this tool is better for fidelity to speed ratio..**\n\n## what you get\n\nJSON output with metadata for every element:\n\n```json\n{\n  \"type\": \"heading\",\n  \"text\": \"Step 1. Gather threat intelligence\",\n  \"bbox\": [64.00, 173.74, 491.11, 218.00],\n  \"font_size\": 21.64,\n  \"font_weight\": \"bold\"\n}\n```\n\ninstead of splitting on word count, use bounding boxes to find semantic boundaries. detect headers and footers by y-coordinate. tables come back with cell-level structure. you control the chunking logic completely.\n\n## comparison\n\n| Tool            | Speed (pps) | Quality                                | Tables | JSON Output      | Best For                          |\n| --------------- | ----------- | -------------------------------------- | ------ | ---------------- | --------------------------------- |\n| pymupdf4llm-C   | ~300        | Good                                   | Yes    | Yes (structured) | large volume, RAG, parsing easily |\n| pymupdf4llm     | ~10         | Good                                   | Yes    | Markdown         | General extraction                |\n| pymupdf (alone) | ~250        | Subpar for any non text only documents | No     | No (text only)   | basic text extraction             |\n| marker          | ~0.5-1      | Excellent                              | Yes    | Markdown         | Maximum fidelity                  |\n| docling         | ~2-5        | Good+                                  | Yes    | JSON             | Document intelligence             |\n| PaddleOCR       | ~20-50      | Good (OCR)                             | Yes    | Text             | Scanned documents                 |\n\n**the tradeoff:** speed and control over automatic extraction. marker and docling give higher fidelity if you have time; this is built for when you don't.\n\n## what it handles well\n\n- high volume PDF ingestion (millions of pages)\n- RAG pipelines where document structure matters for chunking\n- custom downstream processing; you own the logic\n- cost sensitive deployments; CPU only, no expensive inference\n- iteration speed; refine your chunking strategy in minutes\n\n## what it doesn't handle\n\n- scanned or image heavy PDFs (no OCR)\n- 99%+ accuracy on complex edge cases; this trades some precision for speed\n- figures or image extrac"}
{"instruction": "Improving Pydantic memory usage and performance using bitsets", "input": "", "output": "Improving Pydantic memory usage and performance using bitsets\nHey everyone,\n\nI wanted to share a recent blog post I wrote about improving Pydantic's memory footprint:\n\n[https://pydantic.dev/articles/pydantic-bitset-performance](https://pydantic.dev/articles/pydantic-bitset-performance)\n\nThe idea is that instead of tracking model fields that were *explicitly* set during validation using a [`set`](https://docs.python.org/3/tutorial/datastructures.html#sets):\n\n    from pydantic import BaseModel\n\n\n    class Model(BaseModel):\n        f1: int\n        f2: int = 1\n\n    Model(f1=1).model_fields_set\n    #> {'f2'}\n\nWe 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).\n\nThe 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.\n\nDraft PR: https://github.com/pydantic/pydantic/pull/12924.\n\nI’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."}
{"instruction": "Current thoughts on makefiles with Python projects?", "input": "", "output": "Current thoughts on makefiles with Python projects?\nWhat 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:\n\n    default:\n            @echo \"Available commands:\"\n            @echo \"  make check      - Run ty typechecker\"\n            @echo \"  make test       - Run pytest suite\"\n            @echo \"  make clean      - Remove temporary and cache files\"\n            @echo \"  make pristine   - Also remove virtual environment\"\n            @echo \"  make git-prune  - Compress and prune Git database\"\n\n    check:\n            @uv run ty check --color always | less -R\n\n    test:\n            @uv run pytest --verbose\n\n    clean:\n            @# Remove standard cache directories.\n            @find src -type d -name \"__pycache__\" -exec rm -rfv {} +\n            @find src -type f -name \"*.py[co]\" -exec rm -fv {} +\n\n            @# Remove pip metadata droppings.\n            @find . -type d -name \"*.egg-info\" -exec rm -rfv {} +\n            @find . -type d -name \".eggs\" -exec rm -rfv {} +\n\n            @# Remove pytest caches and reports.\n            @rm -rfv .pytest_cache  # pytest\n            @rm -rfv .coverage # pytest-cov\n            @rm -rfv htmlcov  # pytest-cov\n\n            @# Remove type checker/linter/formatter caches.\n            @rm -rfv .mypy_cache .ruff_cache\n\n            @# Remove build and distribution artifacts.\n            @rm -rfv build/ dist/\n\n    pristine: clean\n            @echo \"Removing virtual environment...\"\n            @rm -rfv .venv\n            @echo \"Project is now in a fresh state. Run 'uv sync' to restore.\"\n\n    git-prune:\n            @echo \"Compressing Git database and removing unreferenced objects...\"\n            @git gc --prune=now --aggressive\n\n    .PHONY: default check test clean pristine git-prune\n\nWhat types of things do you have in yours? (If you use one.)"}
{"instruction": "Why doesn’t Python have true private variables like Java?", "input": "", "output": "Why doesn’t Python have true private variables like Java?\nHey everyone\n\nToday I was learning about encapsulation in Python and honestly I got a bit surprised\n\nIn languages like Java we have proper private keywords but in Python it feels like nothing is truly private\nEven with double underscores it just does name mangling and you can still access it if you really want\n\nSo I was wondering why Python is designed this way\n\nIs it because Python follows a different philosophy or is there some deeper reason behind it\n\nAlso in real projects how do developers maintain proper encapsulation if everything can technically be accessed\n\nTrying to understand how to think about this in a more practical and runable way\n\nWould love to hear your thoughts 👍"}
{"instruction": "Choosing a Python task queue library in 2026: Celery vs Dramatiq vs FastStream vs Taskiq vs Repid", "input": "", "output": "Choosing a Python task queue library in 2026: Celery vs Dramatiq vs FastStream vs Taskiq vs Repid\nI wrote a practical comparison of Python task queue libraries in 2026:\n\n[https://aleksul.space/posts/choosing-python-task-queue-library/](https://aleksul.space/posts/choosing-python-task-queue-library/)\n\nIt covers Celery, Dramatiq, FastStream, Taskiq, and Repid, with code examples, broker support, async/sync behavior, production tradeoffs and benchmarks.\n\nThe main takeaways were:\n\n\\- When it comes to throughput, it's important to understand your workload type: I/O or CPU bound makes a huge difference\n\n\\- Asyncio-native frameworks are significantly faster for high-concurrency I/O-bound jobs\n\n\\- For CPU-bound jobs, the library matters much less once the CPU is saturated\n\n\\- Production behavior can vary vastly from framework to framework, same as their philosophy. You have to choose what matters more for your use case\n\nI’d be especially interested to hear from people running these in production. How is your experience running one of these or similar frameworks in production? Is there something that I missed?"}
{"instruction": "A pure Python HTTP Library built on free-threaded Python", "input": "", "output": "A pure Python HTTP Library built on free-threaded Python\nBarq 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.\n\n    from barq import Barq\n\n    app = Barq()\n\n    @app.get(\"/\")\n    def index():\n        return {\"message\": \"Hello, World!\"}\n\n    app.run(workers=4)  # 4 threads, not processes\n\n**Benchmarks (Barq 4 threads vs FastAPI 4 worker processes):**\n\n|Scenario|Barq (4 threads)|FastAPI (4 processes)|\n|:-|:-|:-|\n|JSON|10,114 req/s|5,665 req/s (+79%)|\n|DB query|9,962 req/s|1,015 req/s (+881%)|\n|CPU bound|879 req/s|1,231 req/s (-29%)|\n\nTarget Audience\n\nThis 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.\n\n# Comparison\n\n|Feature|Barq|FastAPI|Flask|\n|:-|:-|:-|:-|\n|Parallelism|Threads (free-threaded)|Processes (uvicorn workers)|Processes (gunicorn)|\n|Async required|No|Yes (for perf)|No|\n|Pure Python|Yes|No (uvloop, etc.)|No (Werkzeug)|\n|Shared memory|Yes (threads)|No (IPC needed)|No (IPC needed)|\n|Production ready|No|Yes|Yes|\n\nThe 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.\n\n**Source code:** [https://github.com/grandimam/barq](https://github.com/grandimam/barq)\n\n**Requirements:** Python 3.13+ with free-threading enabled (`python3.13t`)"}
{"instruction": "Polars Distributed is available on kubernetes", "input": "", "output": "Polars Distributed is available on kubernetes\n[](https://www.reddit.com/r/Python/?f=flair_name%3A%22Showcase%22)^(Disclosure: I am affiliated.)\n\nI 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.\n\nRead more in our announcement:\n\n[https://pola.rs/posts/polars-distributed-available-on-kubernetes/](https://pola.rs/posts/polars-distributed-available-on-kubernetes/)\n\nHappy to answer any questions you might have."}
{"instruction": "Python 2 tooling in 2026", "input": "", "output": "Python 2 tooling in 2026\nFor 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.\n\nI 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.\n\nCan 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.\n\nAre 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?\n\nThank you."}
{"instruction": "I built an in-memory virtual filesystem for Python because BytesIO kept falling short", "input": "", "output": "I built an in-memory virtual filesystem for Python because BytesIO kept falling short\n> UPDATE (Resolved): Visibility issues fixed. Thanks to the mods and everyone for the patience!\n\nI 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.\n\nA 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.\n\nSo I built **D-MemFS** — a pure-Python in-memory filesystem that runs entirely in-process.\n\n    from dmemfs import MemoryFileSystem\n\n    mfs = MemoryFileSystem(max_quota=64 * 1024 * 1024)  # 64 MiB hard limit\n    mfs.mkdir(\"/data\")\n\n    with mfs.open(\"/data/hello.bin\", \"wb\") as f:\n        f.write(b\"hello\")\n\n    with mfs.open(\"/data/hello.bin\", \"rb\") as f:\n        print(f.read())  # b\"hello\"\n\n    print(mfs.listdir(\"/data\"))  # ['hello.bin']\n\n### What My Project Does\n\n- **Hierarchical directories** — not just a flat key-value store\n- **Hard quota enforcement** — writes are rejected *before* they exceed the limit, not after OOM kills your process\n- **Thread-safe** — file-level RW locks + global structure lock; stress-tested under 50-thread contention\n- **Free-threaded Python ready** — works with `PYTHON_GIL=0` (Python 3.13+)\n- **Zero runtime dependencies** — stdlib only, so it won't break when some transitive dependency changes\n- **Async wrapper** included (`AsyncMemoryFileSystem`)\n\n### Target Audience\n\nDevelopers 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.\n\n### Comparison\n\n- **`io.BytesIO`**: Single buffer. No directories, no quota, no thread safety.\n- **`tempfile` / tmpfs**: Hits disk (or requires OS-level setup / admin privileges). Not portable across Windows/macOS/Linux in CI.\n- **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.\n- **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.\n\n346 tests, 97% coverage, Scored 98 on [Socket.dev](https://socket.dev/) supply chain security, Python 3.11+, MIT licensed.\n\nKnown constraints: in-process only (no cross-process sharing), and Python 3.11+ required.\n\nI'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.\n\n**GitHub:** https://github.com/nightmarewalker/D-MemFS\n**PyPI:** `pip install D-MemFS`\n\n---\n\n*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.*"}
{"instruction": "Free book: Master Machine Learning with scikit-learn", "input": "", "output": "Free book: Master Machine Learning with scikit-learn\nHi! I'm the author of [Master Machine Learning with scikit-learn](https://mlbook.dataschool.io/). I just published the book last week, and it's free to read online (no ads, no registration required).\n\nI'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.\n\nIt'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.\n\nHere are the topics I cover:\n\n* Review of the basic Machine Learning workflow\n* Encoding categorical features\n* Encoding text data\n* Handling missing values\n* Preparing complex datasets\n* Creating an efficient workflow for preprocessing and model building\n* Tuning your workflow for maximum performance\n* Avoiding data leakage\n* Proper model evaluation\n* Automatic feature selection\n* Feature standardization\n* Feature engineering using custom transformers\n* Linear and non-linear models\n* Model ensembling\n* Model persistence\n* Handling high-cardinality categorical features\n* Handling class imbalance\n\nQuestions welcome!"}
{"instruction": "Pyrefly v1.3.0 released", "input": "", "output": "Pyrefly v1.3.0 released\nA new version of Pyrefly is out with better type inference, new quick fixes, new configurations, and more.\nhttps://github.com/facebook/pyrefly/releases/tag/1.3.0"}
{"instruction": "What are you using to manage your dev environments in 2026?", "input": "", "output": "What are you using to manage your dev environments in 2026?\nI’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?"}
{"instruction": "I used Pythons standard library to find cases where people paid lawyers for something impossible.", "input": "", "output": "I used Pythons standard library to find cases where people paid lawyers for something impossible.\nI 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.\n\nThe 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\n\ncannot end in discharge. Three data points, one subtraction, one comparison. Attorneys still file these cases and clients still pay.\n\nTech stack: stdlib only. csv, datetime, argparse, re, json, collections. No pip install, no dependencies, Python 3.8+.\n\nProblems I had to solve:\n\n\\- Fuzzy name matching across PACER records. Debtor names have suffixes (Jr., III), \"NMN\" (no middle name)\n\nplaceholders, and inconsistent casing. Had to normalize, strip, then match on first + last tokens to catch middle name\n\nvariations.\n\n\\- Joint case splitting. \"John Smith and Jane Smith\" needs to be split and each spouse matched independently against heir own filing history.\n\n\\- BAPCPA filtering. The statute didn't exist before October 17, 2005, so pre-BAPCPA cases have to be excluded or you get false positives.\n\n\\- Deduplication. PACER exports can have the same case across multiple CSV files. Deduplicate by case ID while keeping attorney attribution intact.\n\nUsage:\n\n$ python screen\\_1328f.py --data-dir ./csvs --target Smith\\_John --control Jones\\_Bob\n\nThe --control flag lets you screen a comparison attorney side by side to see if the violation rate is unusual or normal for the district.\n\nProcesses 100K+ cases in under a minute. Outputs to terminal with structured sections, or --output-json for programmatic use.\n\nGitHub: [https://github.com/ilikemath9999/bankruptcy-discharge-screener](https://github.com/ilikemath9999/bankruptcy-discharge-screener)\n\nMIT licensed. Standard library only. Includes a PACER CSV download guide and sample output.\n\nLet me know what you think friends.  Im a first timer here."}
{"instruction": "A new Python file-based routing web framework", "input": "", "output": "A new Python file-based routing web framework\nHello, 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.\n\ndocs: https://plasmacan.github.io/cylinder/\n\nsrc: https://github.com/plasmacan/cylinder\n\n**What My Project Does**\n\nCylinder is a lightweight WSGI web framework for Python that uses file-based routing to keep web apps simple, readable, and predictable.\n\n**Target Audience**\n\nPython developers who want more structure than a microframework, but less complexity than a full-stack framework.\n\n**Comparison**\n\nCylinder sits between Flask-style flexibility and Django-style convention, offering clear project structure and low boilerplate without hiding request flow behind heavy abstractions.\n\n(None of the code was written by AI)"}
{"instruction": "Python Crash Course Notebook for Data Engineering", "input": "", "output": "Python Crash Course Notebook for Data Engineering\nHey everyone! Sometime back, I put together a **crash course on Python** specifically tailored for Data Engineers. I hope you find it useful! I have been a data engineer for **5+ years** and went through various blogs, courses to make sure I cover the essentials along with my own experience.\n\nFeedback and suggestions are always welcome!\n\n📔 **Full Notebook:** [Google Colab](https://colab.research.google.com/drive/1r_MmG8vxxboXQCCoXbk2nxEG9mwCjnNy?usp=sharing)\n\n🎥 **Walkthrough Video** (1 hour): [YouTube](https://youtu.be/IJm--UbuSaM) \\- Already has almost **20k views & 99%+ positive ratings**\n\n💡 Topics Covered:\n\n**1. Python Basics** \\- Syntax, variables, loops, and conditionals.\n\n**2. Working with Collections** \\- Lists, dictionaries, tuples, and sets.\n\n**3. File Handling** \\- Reading/writing CSV, JSON, Excel, and Parquet files.\n\n**4. Data Processing** \\- Cleaning, aggregating, and analyzing data with pandas and NumPy.\n\n**5. Numerical Computing** \\- Advanced operations with NumPy for efficient computation.\n\n**6. Date and Time Manipulations**\\- Parsing, formatting, and managing date time data.\n\n**7. APIs and External Data Connections** \\- Fetching data securely and integrating APIs into pipelines.\n\n**8. Object-Oriented Programming (OOP)** \\- Designing modular and reusable code.\n\n**9. Building ETL Pipelines** \\- End-to-end workflows for extracting, transforming, and loading data.\n\n**10. Data Quality and Testing** \\- Using \\`unittest\\`, \\`great\\_expectations\\`, and \\`flake8\\` to ensure clean and robust code.\n\n**11. Creating and Deploying Python Packages** \\- Structuring, building, and distributing Python packages for reusability.\n\n**Note:** I have not considered PySpark in this notebook, I think PySpark in itself deserves a separate notebook!"}
{"instruction": "Python 3.9 to 3.14 performance benchmark", "input": "", "output": "Python 3.9 to 3.14 performance benchmark\nHi everyone\n\nAfter publishing our Node.js benchmarks, I got a bunch of requests to benchmark Python next. So I ran the same style of microbenchmarks across Python 3.9 through 3.14.\n\n|Benchmark|3.9.25|3.10.19|3.11.14|3.12.12|3.13.11|3.14.2|\n|:-|:-|:-|:-|:-|:-|:-|\n|HTTP GET throughput (MB/s)|9.2|9.5|11.0|10.6|10.6|10.6|\n|json.loads (ops/s)|63,349|64,791|59,948|56,649|57,861|53,587|\n|json.dumps (ops/s)|29,301|30,185|30,443|32,158|31,780|31,957|\n|SHA-256 throughput (MB/s)|3,203.5|3,197.6|3,207.1|3,201.7|3,202.2|3,208.1|\n|Array map + reduce style loop (ops/s)|16,731,301|17,425,553|20,034,941|17,875,729|18,307,005|18,918,472|\n|String build with join (MB/s)|3,417.7|3,438.9|3,480.5|3,589.9|3,498.6|3,581.6|\n|Integer loop randomized (ops/s)|6,635,498|6,789,194|6,909,192|7,259,830|7,790,647|7,432,183|\n\nFull charts and all benchmarks are available hers: [Full Benchmark](https://www.repoflow.io/blog/python-3-9-to-3-14-performance-benchmarks)\n\nLet me know if you’d like me to benchmark more"}
{"instruction": "Protection against attacks like what happened with LiteLLM?", "input": "", "output": "Protection against attacks like what happened with LiteLLM?\nYou’ve probably heard that the LiteLLM package got hacked (https://github.com/BerriAI/litellm/issues/24512). I’ve been thinking about how to defend against this:\n\n1. **Using lock files** \\- this can keep us safe from attacks in new versions, but it’s a pain because it pins us to older versions and we miss security updates.\n2. **Using a sandbox environment** \\- like developing inside a Docker container or VM. Safer, but more hassle to set up.\n\nAnother question: as a maintainer of a library that depends on dozens of other libraries, how do we protect our users? Should we pin every package in the pyproject.toml?\n\nMaybe it indicates a need in the whole ecosystem.\n\nWould love to hear how you handle this, both as a user and as a maintainer. What should be improved in the whole ecosystem to prevent such attacks?"}
{"instruction": "LocalStack is no longer free — I built MiniStack, a free open-source alternative with 20 AWS service", "input": "", "output": "LocalStack is no longer free — I built MiniStack, a free open-source alternative with 20 AWS service\nIf 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.\n\nI 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.\n\n\\*\\*What it covers:\\*\\*\n\n\\- Core: S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, Secrets Manager, CloudWatch Logs\n\n\\- Extended: SSM Parameter Store, EventBridge, Kinesis, CloudWatch Metrics, SES, Step Functions\n\n\\- Real infrastructure: RDS (actual Postgres/MySQL containers), ElastiCache (actual Redis), ECS (actual Docker containers), Glue, Athena (real SQL via DuckDB)\n\n\\*\\*Key differences from LocalStack:\\*\\*\n\n\\- MIT licensed (not BSL)\n\n\\- No account or API key required\n\n\\- \\~2s startup vs \\~30s\n\n\\- \\~30MB RAM vs \\~500MB\n\n\\- 150MB image vs \\~1GB\n\n\\- RDS/ElastiCache/ECS spin up real containers (LocalStack Pro-only features)\n\n\\`\\`\\`bash\n\ndocker run -p 4566:4566 nahuelnucera/ministack\n\naws --endpoint-url=http://localhost:4566 s3 mb s3://test-bucket\n\n\\`\\`\\`\n\nGitHub: [https://github.com/Nahuel990/ministack](https://github.com/Nahuel990/ministack)\n\nWebsite: [https://ministack.org](https://ministack.org)\n\nHappy to take questions or feature requests."}
{"instruction": "rut - A unittest runner that skips tests unaffected by your changes", "input": "", "output": "rut - A unittest runner that skips tests unaffected by your changes\n**What My Project Does**\n\n`rut` is a test runner for Python's `unittest`. It analyzes your import graph to:\n\n1. **Order tests by dependencies** — foundational modules run first, so when something breaks you see the root cause immediately, not 300 cascading failures.\n2. **Skip unaffected tests** — `rut --changed` only runs tests that depend on files you modified. Typically cuts test time by 50-80%.\n\nAlso supports async tests out of the box, keyword filtering (`-k \"auth\"`), fail-fast (`-x`), and coverage (`--cov`).\n\n    pip install rut\n    rut              # all tests, smart order\n    rut --changed    # only affected tests\n    rut -k \"auth\"    # filter by name\n\n**Target Audience**\n\nPython developers using unittest who want a modern runner without switching frameworks.\n\nAlso pytest users who want built-in async support and features like dependency ordering and affected-only test runs that pytest doesn't offer out of the box.\n\n**Comparison**\n\n* python -m unittest: No smart ordering, no way to skip unaffected tests, no -k, no coverage. rut adds what's missing.\n* pytest: Great ecosystem and plugin support. rut takes a different approach — instead of replacing the test framework, it focuses on making the runner itself smarter (dependency ordering, affected-only runs) while staying on stdlib unittest.\n\n[https://github.com/schettino72/rut](https://github.com/schettino72/rut)"}
{"instruction": "I’m starting coding from scratch – is Python really the best first language?", "input": "", "output": "I’m starting coding from scratch – is Python really the best first language?\nI’m completely new to coding and trying to choose my first programming language.\n\nI see Python recommended everywhere because it’s beginner-friendly and versatile.\n\nMy goal is to actually build things, not just watch tutorials forever.\n\nFor those who started with Python:\n– Was it a good decision?\n– What should I focus on in the first 30 days?"}
{"instruction": "I replaced FastAPI with Pyodide: My visual ETL tool now runs 100% in-browser", "input": "", "output": "I replaced FastAPI with Pyodide: My visual ETL tool now runs 100% in-browser\n# I swapped my FastAPI backend for Pyodide — now my visual Polars pipeline builder runs 100% in the browser\n\nHey r/Python,\n\nI'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.\n\nQuick 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.\n\n**Try it:** [demo.flowfile.org](https://demo.flowfile.org)\n\n**What My Project Does**\n\nBuild 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.\n\n**How Pyodide Makes This Work**\n\nLoad Python + Polars + Pydantic in the browser:\n\n    const pyodide = await window.loadPyodide({\n        indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.27.7/full/'\n    })\n    await pyodide.loadPackage(['numpy', 'polars', 'pydantic'])\n\nThe execution engine stores LazyFrames to keep memory flat:\n\n    _lazyframes: Dict[int, pl.LazyFrame] = {}\n\n    def store_lazyframe(node_id: int, lf: pl.LazyFrame):\n        _lazyframes[node_id] = lf\n\n    def execute_filter(node_id: int, input_id: int, settings: dict):\n        input_lf = _lazyframes.get(input_id)\n        field = settings[\"filter_input\"][\"basic_filter\"][\"field\"]\n        value = settings[\"filter_input\"][\"basic_filter\"][\"value\"]\n        result_lf = input_lf.filter(pl.col(field) == value)\n        store_lazyframe(node_id, result_lf)\n\nThen from the frontend, just call it:\n\n    pyodide.globals.set(\"settings\", settings)\n    const result = await pyodide.runPythonAsync(`execute_filter(${nodeId}, ${inputId}, settings)`)\n\nThat's it — the browser is now a Python runtime.\n\n**Code Generation**\n\nThe web version also supports the code generator — click \"Generate Code\" and get clean Python:\n\n    import polars as pl\n\n    def run_etl_pipeline():\n        df = pl.scan_csv(\"customers.csv\", has_header=True)\n        df = df.group_by([\"Country\"]).agg([pl.col(\"Country\").count().alias(\"count\")])\n        return df.sort([\"count\"], descending=[True]).head(10)\n\n    if __name__ == \"__main__\":\n        print(run_etl_pipeline().collect())\n\nNo Flowfile dependency — just Polars.\n\n**Target Audience**\n\nData engineers who want to prototype pipelines visually, then export production-ready Python.\n\n**Comparison**\n\n* Pandas/Polars alone: No visual representation\n* Alteryx: Proprietary, expensive, requires installation\n* KNIME: Free desktop version exists, but it's a heavy install best suited for massive, complex workflows\n* This: Lightweight, runs instantly in your browser — optimized for quick prototyping and smaller workloads\n\n**About the Browser Demo**\n\nThis 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.\n\n**On performance:** Browser version depends on your memory. For datasets under \\~100MB it feels snappy.\n\n**Links**\n\n* Live demo (lite): [demo.flowfile.org](https://demo.flowfile.org)\n* Full version + docs: [github.com/Edwardvaneechoud/Flowfile](https://github.com/Edwardvaneechoud/Flowfile)"}
{"instruction": "Understanding multithreading & multiprocessing in Python", "input": "", "output": "Understanding multithreading & multiprocessing in Python\nI 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.\n\nI wrote a [short blog post](https://anmols.bearblog.dev/understanding-multithreading-and-multiprocessing-in-python/)‚ with [figures and code](https://github.com/AnmolS99/multithreading-multiprocessing-python), giving an overview of these, which hopefully will be helpful for others looking to serve their backend more efficiently 😊\n\nFeedback and corrections are very welcome!"}
{"instruction": "Packaging a Python library with a small C dependency —", "input": "", "output": "Packaging a Python library with a small C dependency —\nhow do you handle install reliability?\n\nHey folks,\n\nI’ve run into a bit of a packaging dilemma and wanted to get some opinions from people who’ve dealt with similar situations.\n\nI’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.\n\nHere’s where I’m stuck:\n\n* If I rely on local compilation during `pip install`, users without a proper C toolchain are going to hit installation failures.\n* 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.\n* 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.\n\nThere *is* a fallback option I’ve considered:\n\n* Detect at import time whether the compiled extension loaded successfully.\n* If not, fall back to a pure Python implementation.\n\nBut 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.\n\nSo I’m trying to balance:\n\n* Ease of installation (no failures)\n* Cross-platform support\n* Performance/accuracy (native C vs fallback)\n* Maintenance overhead (CI pipelines, wheel builds, etc.)\n\n**Questions:**\n\n1. In 2026, is it basically expected to ship prebuilt wheels for all major platforms if you include any C code?\n2. Would you accept a degraded Python fallback, or just fail hard if the extension doesn’t compile?\n3. Any strong opinions on `cffi` vs `ctypes` for this kind of use case?\n4. How much effort is “normal” to invest in multi-platform wheel builds for a small but critical C dependency?\n\nWould love to hear how others approach this tradeoff in real-world libraries.\n\nThanks!"}
{"instruction": "How the telnyx PyPI package was compromised - malware hidden inside WAV audio files", "input": "", "output": "How the telnyx PyPI package was compromised - malware hidden inside WAV audio files\nOn March 27, the official telnyx package (v4.87.1 and v4.87.2) was compromised on PyPI by a threat actor called TeamPCP. The package averages around 30,000 downloads/day. We wrote a full breakdown on how the stenography works, a Python encoder/decoder, detection methods and practical defense steps in the tutorial available here: [https://pwn.guide/free/cryptography/audio-steganography](https://pwn.guide/free/cryptography/audio-steganography)"}
{"instruction": "Showcase: pathgenerator — A library for generating non-deterministic mouse movements", "input": "", "output": "Showcase: pathgenerator — A library for generating non-deterministic mouse movements\nHi r/Python,\n\nI’d like to share **pathgenerator**, an open‑source Python library for generating realistic, human-like mouse cursor paths. Unlike traditional automation tools that move in straight lines or simple Bezier curves, this library simulates the actual physics of a human hand using a **Proportional-Derivative (PD) Controller**.\n\n**Source Code**\n\n* \\*\\*PyPI:\\*\\*[https://pypi.org/project/pathgenerator/](https://pypi.org/project/pathgenerator/)\n* **GitHub:** \\[Link to your GitHub Repo\\] *(*[*https://github.com/sockheadrps/Path-Generator*](https://github.com/sockheadrps/Path-Generator)*)*\n* **Documentation:** [https://sockheadrps.github.io/Path-Generator/](https://sockheadrps.github.io/Path-Generator/)\n\nWhat pathgenerator Does\n\npathgenerator calculates cursor trajectories by simulating a mass (the cursor) being pulled towards a target by a force, while being dampened by friction. This naturally creates artifacts found in human motion, such as:\n\n* **Fitts's Law behavior:** Fast acceleration and slow, precise braking near the target.\n* **Overshoots:** The cursor can miss the target slightly and correct itself, just like a real hand.\n* **Arcs:** Natural curvature rather than robotic straight lines.\n* **Jitter/Noise:** Micro-variations that prevent distinct algorithmic patterns.\n\n`pip install pathgenerator`\n\nIt includes an optional **Windows Emulator** (via `pywin32`) to execute these paths on your actual desktop\n\n`pip install pathgenerator[windows]`\n\nand a **Playground Server** to visualize the paths in a browser.\n\n`pip install pathgenerator[server]`\n\nTarget Audience\n\nThis library is intended for developers who need to:\n\n* Create undetectable automation bots or testing scripts.\n* Generate synthetic data for training Human-Computer Interaction (HCI) models.\n* Test UI/UX with \"imperfect\" user inputs rather than instantaneous clicks.\n\nComparison\n\nBelow is a comparison between pathgenerator and standard automation libraries like pyautogui or simple Bezier curve implementations.\n\n|**Aspect**|**pathgenerator**|**Traditional Automation (PyAutoGUI)**|**Bezier Curves**|\n|:-|:-|:-|:-|\n|**Movement Logic**|**Physics-based** (PD Controller). Simulates mass, thrust, and drag.|**Linear**. Moves in a straight line with constant speed.|**Geometric**. Smooth curves, but mathematically perfect.|\n|**Realism**|**High**. Includes overshoots, reaction delays, and corrective movements.|**None**. Instant and robotic.|**Medium**. Looks smooth but lacks human \"noise\" and physics.|\n|**Detectability**|**Low**. Hard to distinguish from real human input.|**High**. Trivial to detect anti-cheat or bot protection.|**Medium**. Patterns can often be statistically detected.|\n|**Configuration**|Tunable \"knobs\" for velocity, noise, and overshoot probability.|Usually just duration/speed.|Control points for curve shape.|\n\nExample using the optional windows cursor emulator (pathgenerator\\[windows\\])\n\n```python\nfrom pathgenerator import PDPathGenerator, PathEmulator\n\n# 1. Initialize the Generator\ngen = PDPathGenerator()\n\n# 2. Generate a path from (100, 100) to (1800, 900)\n# Returns a numpy array of coordinates\npath, progress, steps, params = gen.generate_path(\n    start_x=100.0,\n    start_y=100.0,\n    end_x=1800.0,\n    end_y=900.0,\n    mouse_velocity=0.65, # Speed factor (0.1 to 1.0)\n    noise=2.5,           # Amount of human jitter\n    overshoot_prob=0.8   # Chance to overshoot the target\n)\n\n#"}
{"instruction": "Mastering Asyncio Synchronization: A Python Guide", "input": "", "output": "Mastering Asyncio Synchronization: A Python Guide\n[https://sidaliassoul.com/blog/mastering-asyncio-synchronization-python-guide](https://sidaliassoul.com/blog/mastering-asyncio-synchronization-python-guide)\n\nA common beginner mistake when starting out with asynchronous programming is thinking that your code is safe from race conditions just because it runs in a single thread.\n\n**That’s totally wrong!**\n\nDespite running in a single thread, async code runs concurrently. This means that as long as there is an `await` keyword inside your async function, your program is prone to race conditions.\n\nThe reason is simple: as soon as an `await` line is executed, the decision of whether to proceed or switch to another coroutine is left entirely to the event loop.\n\nPicture this: a credit coroutine reads a shared balance, awaits an I/O-bound task for a second, and then increments the previously read balance by 1.\n\n    async def credit():\n      global balance\n      # read balance\n      current_balance = balance # read current balance\n      await asyncio.sleep(1) # Simulate an I/O-bound task.\n      # write new balance balance\n      balance = current_balance + 1\n\n\nIf you run these concurrently, you risk a race condition. Because the read and write operations are separated by an **await**, each coroutine can be paused at that point. While the first coroutine is suspended, another runs and updates the balance; when the first coroutine resumes, it overwrites the second one's work. This is known as a **lost update race condition**!"}
{"instruction": "What is your approach to PyPI dependency hygiene after recent supply chain attacks?", "input": "", "output": "What is your approach to PyPI dependency hygiene after recent supply chain attacks?\nThe telnyx compromise was a good reminder that PyPI trust is not a given. Curious how other Python developers are actually handling this in practice, not just in theory.\n\nI use version pinning in most of my projects but I don't have a consistent rule for when to update. Some people use tools like pip-audit or dependabot, others just pin everything and manually review changelogs. There's also the question of how much you trust a package at all, since even well-established ones can rotate ownership or get compromised.\n\nDo you have a class of packages you trust more than others, Are there specific tools or workflows you'd recommend for keeping an eye on what you have installed, Or do you mostly just accept the risk and move on?"}
{"instruction": "formualizer: an Arrow-backed spreadsheet engine - 320+ functions, incremental recalc, PyO3 + Rust", "input": "", "output": "formualizer: an Arrow-backed spreadsheet engine - 320+ functions, incremental recalc, PyO3 + Rust\n```\npip install formualizer\n```\n\n```python\nimport formualizer as fz\n\n# Recalculate every formula in an xlsx and write it back - one call\nfz.recalculate_file(\"model.xlsx\", output=\"recalculated.xlsx\")\n\n# Or drive it programmatically\nwb = fz.load_workbook(\"model.xlsx\")\nwb.set_value(\"Assumptions\", 3, 2, 0.08)  # swap in a new interest rate\nwb.evaluate_all()\n\nprint(wb.evaluate_cell(\"Summary\", 5, 3))  # =IRR(...)\nprint(wb.evaluate_cell(\"Summary\", 6, 3))  # =NPV(...)\nprint(wb.evaluate_cell(\"Summary\", 7, 3))  # =PMT(...)\n```\n\n**GitHub:** https://github.com/psu3d0/formualizer\n**Docs:** https://www.formualizer.dev\n\n---\n\n**Why this exists**\n\nPython's Excel formula situation sucks:\n\n- **openpyxl** reads and writes `.xlsx` perfectly, evaluates zero formulas. Cells with `=SUM(A1:A10)` return `None` unless Excel already cached the values when someone last saved the file.\n- **xlcalc** actually evaluates, but covers around 50 functions. `XLOOKUP`, `SUMIFS` with multiple criteria, `IRR`, `XIRR`, dynamic arrays (`FILTER`, `UNIQUE`, `SORT`) — not there.\n- **xlwings** works if Excel is installed on the machine. Useless in Docker or on Linux.\n\nThe standard workaround - pre-calculate in Excel, save cached values, read with openpyxl - falls apart when someone changes the model, or you need to evaluate the same workbook across thousands of different inputs. Or even just need to evaluate real workbooks of non-trivial size.\n\n`formualizer` is a Rust formula engine with PyO3 bindings. No Excel. No COM. Runs anywhere Python runs.\n\n---\n\n**Bonus: register Python functions as Excel formulas**\n\n```python\ndef risk_score(grid):\n    flat = [v for row in grid for v in row]\n    return sum(v ** 2 for v in flat) / len(flat)\n\nwb.register_function(\"RISK_SCORE\", risk_score, min_args=1, max_args=1)\nwb.set_formula(\"Sheet1\", 5, 1, \"=RISK_SCORE(A1:D100)\")\n\nresult = wb.evaluate_cell(\"Sheet1\", 5, 1)\n```\n\nYour callback participates in the dependency graph like any built-in - change a cell in `A1:D100` and it recalculates on the next `evaluate_all()`.\n\n---\n\n**Comparison**\n\n| Library | Evaluates | Functions | Dep. graph | Write xlsx | No Excel | License |\n|---|---|---|---|---|---|---|\n| **formualizer** | ✅ | 320+ | ✅ incremental | ✅ | ✅ | MIT / Apache-2.0 |\n| xlcalc | ✅ | ~50 | partial | ❌ | ✅ | MIT |\n| openpyxl | ❌ | — | ❌ | ✅ | ✅ | MIT |\n| xlwings | ✅ | ~400* | ❌ | ✅ | ❌ | BSD |\n\nFormal benchmarks are in progress. Rust core, incremental dependency graph (only affected cells recalculate on edits), MIT/Apache-2.0.\n\nThis library is **fast.**\n\n---\n\n**What My Project Does**\n\nPython library for evaluating Excel formulas without Excel installed. Rust core via PyO3. 320+ Excel-compatible functions, `.xlsx` read/write, incremental dependency graph, custom Python formula callbacks, deterministic mode for reproducible evaluation. MIT/Apache-2.0.\n\n**Target Audience**\n\nData engineers pulling business logic out of Excel workbooks, fintech/insurance teams running server-side formula evaluation (pricing, amortization, risk), SaaS builders who need spreadsheet logic without a server-side Excel dependency."}
{"instruction": "Cutting Python Web App Memory Over 31%", "input": "", "output": "Cutting Python Web App Memory Over 31%\nOver 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.\n\nTurned 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:\n\n1. **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.\n2. **Raw + DC database pattern**: Dropped MongoEngine for raw queries + slotted dataclasses. 100 MB saved per worker \\*and\\* nearly doubled requests/sec.\n3. **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.\n4. **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.)\n5. **Moved caches to diskcache**: Small-to-medium in-memory caches shifted to disk. Modest savings but it adds up.\n\nTotal 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/](https://mkennedy.codes/posts/cutting-python-web-app-memory-over-31-percent/)"}
{"instruction": "Python 3.14.7 and 3.13.15 are now available!", "input": "", "output": "Python 3.14.7 and 3.13.15 are now available!\nBug fix releases for Python 3.13 and Python 3.14.\n\n[https://blog.python.org/2026/08/python-[PHONE]/](https://blog.python.org/2026/08/python-[PHONE]/)"}
{"instruction": "Library dependency version specifiers aren't for fixing vulnerabilities", "input": "", "output": "Library dependency version specifiers aren't for fixing vulnerabilities\nhttps://sethmlarson.dev/library-version-specifiers-not-for-vulnerabilities\n\nA blog post from Seth Larson, the Security-in-Residence Developer for the Python Software Foundation."}
{"instruction": "slamd - a dead simple 3D visualizer for Python", "input": "", "output": "slamd - a dead simple 3D visualizer for Python\n# What My Project Does\n\nslamd is a GPU-accelerated 3D visualization library for Python. pip install slamd, write 3 lines of code, and you get an interactive 3D viewer in a separate window. No event loops, no boilerplate. Objects live in a transform tree - set a parent pose and everything underneath moves. Comes with the primitives you actually need for 3D work: point clouds, meshes, camera frustums, arrows, triads, polylines, spheres, planes.\n\nC++ OpenGL backend, FlatBuffers IPC to a separate viewer process, pybind11 bindings. Handles millions of points at interactive framerates.\n\n# Target Audience\n\nAnyone doing 3D work in Python - robotics, SLAM, computer vision, point cloud processing, simulation. Production-ready (pip install with wheels on PyPI for Linux and macOS), but also great for quick prototyping and debugging.\n\n# Comparison\n\nMatplotlib 3D - software rendered, slow, not real 3D. Slamd is GPU-accelerated and handles orders of magnitude more data.\n\nRerun - powerful logging/recording platform with timelines and append-only semantics. Slamd is stateful, not a logger - you set geometry and it shows up now. Much smaller API surface.\n\nOpen3D - large library where visualization is one feature among many. Slamd is focused purely on viewing, with a simpler API and a transform tree baked in.\n\nRViz - requires ROS. Slamd gives you the same transform-tree mental model without the ROS dependency.\n\nGithub: https://github.com/Robertleoj/slamd"}
{"instruction": "Thank You | from Nova", "input": "", "output": "Thank You | from Nova\nHello!\nI'm Nova, I'm a college student taking CS in Norway. And I just wanted to share a bit of my story.\n\nI started my developing career roughly 7 years ago when I was 8-9. I remember watching so many movies about these hackers and programmers growing up, and thinking \"Wow, I wish I could be like them!\". Luckily my father had a computer science background himself! So he saw this and showed me a couple things such as Scratch, blablabla.\nI quickly quit Scratch, cause I thought it was boring and hard. But just a few months later, I installed Python and VSCode on the family computer! I started watching a multi hour Python course by Programming with Mosh and followed along. I remember being so bored haha!\n\nBut it clicked. It really did. It scratched (pardon the pun) something that Scratch couldn't. Some abstract yet so understandable logic. At the time it really felt like I was on top of the whole world.\nSomewhere in the second last to last years of primary school, I was fully invested. I was making calculator apps and whatever I could think of during the free time at school with the provided iPads that hadn't been there the year before. Heck! I got some other kids in my class to become interested in programming too!\n\nEventually, a year later when I started middle school/high school (combined into the same three years in Norway), I naturally started learning new things such as Java and C# .NET. My Python usage was mostly just small prototypes for other languages at that time.\n\nYet I never abandoned it. Not even now.\nPython is what started my journey, and I am so grateful for everything it has done.\n\nSo thank you,\nThank all of you,\n\nThank you every random StackOverflow member who posted weirdly specific help threads.\n\nThank you every StackOverflow member who responded to my silly little questions.\n\nThank you to all the Python maintainers and contributors.\n\nThank you Guido van Rossum for founding the language.\n\nAnd thank you to the whole Python community who made this student's childhood dreams possible and bloom to life.\n\n\\- Nova"}
{"instruction": "Pyrefly v0.52.0 - Even Faster Than Before", "input": "", "output": "Pyrefly v0.52.0 - Even Faster Than Before\n# What it is\n\nPyrefly is a type checker and language server for Python, which provides lightning-fast type checking along with IDE features such as code navigation, semantic highlighting, code completion, and powerful refactoring capabilities. It is available as a command-line tool and an extension for popular IDEs and editors such as VSCode, Neovim, Zed, and more.\n\nThe new v0.52.0 release brings a number of performance optimizations.\n\nFull release notes: [LINK](https://github.com/facebook/pyrefly/releases/edit/0.52.0)\n\nGithub repo: [LINK](https://github.com/facebook/pyrefly)\n\n# What's New\n\nAs we’ve been watching Winter Olympic athletes racing for gold, we’ve been inspired by their dedication to keep pushing our own bobsled towards our goals of making [Pyrefly](https://pyrefly.org) as performant as possible.\n\nJust as milliseconds count in speed skating, they also matter when it comes to type checking diagnostics\\! With this release, Pyrefly users can benefit from a range of speed and memory improvements, which we’ve summarised below. But this is just the first lap, the race isn’t over\\! We’ve got even more optimizations planned before our v1.0 release later this year, along with cool new features and tons of bug fixes, so stay tuned.\n\n### 18x Faster Updated Diagnostics After Saving a File\n\nWe’ve significantly improved the speed at which type errors and diagnostics appear in your editor after saving a file. Thanks to fine-grained dependency tracking and streaming diagnostics, Pyrefly now updates error messages almost instantly,even in large codebases. In edge cases that previously took several seconds, updates now typically complete in under 200ms. For a deep dive into how we achieved this, check out our [latest blog post](https://pyrefly.org/blog/2026/02/06/performance-improvements/).\n\n### 2–3x Faster Initial Indexing Time\n\nThe initial indexing process (i.e. when Pyrefly scans your project and builds its internal type map) has been optimized for speed. This means the editor starts up faster and is more responsive, even in repositories with many dependencies.\n\n### 40–60% Less Memory Usage\n\nWe’ve made significant improvements to Pyrefly’s memory efficiency. The language server now uses 40–60% less RAM, allowing Pyrefly to run more smoothly on resource-constrained machines.\nNote: The above stats are for the pytorch repo, using a Macbook Pro. Exact improvements will vary based on your machine and project. If you run into any issues using Pyrefly on your project, please file an issue on our Github."}
{"instruction": "I built a civic transparency platform with FastAPI that aggregates 40+ government APIs", "input": "", "output": "I built a civic transparency platform with FastAPI that aggregates 40+ government APIs\n**What My Project Does:**\n\nWeThePeople 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.\n\n**Target Audience:**\n\nJournalists, 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.\n\n**How Python Relates:**\n\nThe entire backend is Python. FastAPI, SQLAlchemy, and 36 API connectors that each wrap a different government data source.\n\nThe 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.\n\nThe 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.\n\nThe 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).\n\nAll 36 API connectors follow the same pattern. Each wraps a government API (Senate LDA, USASpending, FEC, [Congress.gov](http://Congress.gov), SEC EDGAR, Federal Register, OpenFDA, EPA, FARA, and more) with retry logic, caching, and circuit breaker integration.\n\nThe claims verification pipeline extracts assertions from text and matches them against 9 data sources using a multi-matcher architecture.\n\nRuns on a $4 monthly Hetzner ARM server. 4.1GB SQLite database in WAL mode. Let's Encrypt TLS via certbot.\n\n**Source code:** [github.com/Obelus-Labs-LLC/WeThePeople](http://github.com/Obelus-Labs-LLC/WeThePeople)\n\n**Live:** [wethepeopleforus.com](http://wethepeopleforus.com)"}
{"instruction": "The 8 year old issue on pth files.", "input": "", "output": "The 8 year old issue on pth files.\nContext but skip ahead if you are aware:  To get up to speed on why everyone is talking about pth/site files - (note this is not me, not an endorsement) - https://www.youtube.com/watch?v=mx3g7XoPVNQ \"A bad day to use Python\" by Primetime\n\ntl;dw & skip ahead - code execution in pth/site files feel like a code sin that is easy to abuse yet cannot be easily removed now, as evidence by this issue https://github.com/python/cpython/issues/78125 \"Deprecate and remove code execution in pth files\" that was first opened in June, 2018 and mysteriously has gotten some renewed interest as of late \\s.\n\nI've been using Python since ~2000 when I first found it embedded in a torrent (utorrent?) app I was using.  Fortunately It wasn't until somewhere around 2010~2012 that in the span of a week I started a new job on Monday and quit by Wednesday after I learned how you can abuse them.\n\nMy stance is they're overbooked/doing too much and I think the solution is somewhere in the direction of splitting them apart into two new files.   That said, something needs to change besides swapping `/usr/bin/python` for a wrapper that enforces adding \"-S\" to everything."}
{"instruction": "A comparison of Rust-like fluent iterator libraries", "input": "", "output": "A comparison of Rust-like fluent iterator libraries\nI mostly program in Python, but I have fallen in love with Rust's beautiful iterator syntax. Trying to chain operations in Python is ugly in comparison. The inside-out nested function call syntax is hard to read and write, whereas Rust's method chaining is much clearer. List comprehensions are great and performant but with more complex conditions they become unwieldy.\n\nThis is what the different methods look like in the (somewhat contrived) example of finding all the combinations of two squares from 1^2 to 4^2 such that their sum is greater than 6, then sorting from smallest to largest sum.\n\n    # List comprehension\n    foo = list(\n        sorted(\n            [\n                combo\n                for combo in itertools.combinations(\n                    [x*x for x in range(1, 5)],\n                    2\n                )\n                if sum(combo) > 6\n            ],\n            key=lambda combo: sum(combo)\n        )\n    )\n\n    # For loop\n    foo = []\n    for combo in itertools.combinations([x*x for x in range(1, 5)], 2):\n        if sum(combo) > 6:\n            foo.append(combo)\n    foo.sort(key=lambda combo: sum(combo))\n\n    # Python functions\n    foo = list(\n        sorted(\n            filter(\n                lambda combo: sum(combo) > 6,\n                itertools.combinations(\n                    map(\n                        lambda x: x*x,\n                        range(1, 5)\n                    ),\n                    2\n                )\n            ),\n            key=lambda combo: sum(combo)\n        )\n    )\n\n    # Fluent iterator\n    foo = (fluentiter(range(1, 5))\n        .map(lambda x: x*x)\n        .combinations(2)\n        .filter(lambda combo: sum(combo) > 6)\n        .sort(key=lambda combo: sum(combo))\n        .collect()\n    )\n\nThe list comprehension is great for simple filter-map pipelines, but becomes inelegant when you try to tack more operations on. The for loop is clean, but requires multiple statements (this isn't necessarily a bad thing). Python nested functions are hard to read. Fluent iterator syntax is clean and runs as a single statement.\n\nIt's up to personal preference if you prefer this syntax or not. I'm not trying to convince you to change how you code, only to maybe give fluent iterators a try. If you are already a fan of fluent iterator syntax, then you can hopefully use this post to decide on a library.\n\nMany Python programmers do seem to like this syntax, which is why there are numerous libraries implementing fluent iterator functionality. I will compare 6 such libraries in this post:\n\n* [QWList](https://pypi.org/project/qwlist/)\n* [F-IT](https://pypi.org/project/f-it/)\n* [FluentIter](https://pypi.org/project/fluentiter/)\n* [Rustiter](https://pypi.org/project/rustiter/)\n* [Pyochain](https://pypi.org/project/pyochain/)\n* [PyFunctional](https://pypi.org/project/pyfunctional/)\n\nThere are undoubtedly more, but these are the ones I could find easily. I am not affiliated with any of these libraries. I tried them all out because I wanted Rust's iterator ergonomics for my own projects.\n\nI am mainly concerned with 1) number of features and 2) performance. Rust has a lot of nice operations built into its [Iterator](https://doc.rust-lang.org/nightly/core/iter/trait.Iterator.html) trait and there are many more in the [itertools](https://docs.rs/itertools/latest/itertools/trait.Itertools.html) crate. I will score these libraries higher for having more built-in features. The"}
{"instruction": "What Every Python Developer Should Know About the CPython ABI", "input": "", "output": "What Every Python Developer Should Know About the CPython ABI\n> 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\".\n\nhttps://labs.quansight.org/blog/python-abi-abi3t"}
{"instruction": "SQLalchemy vs Psycopg3", "input": "", "output": "SQLalchemy vs Psycopg3\nSo I am currently in the process of building my business dashboard, where the backend is fully written in Python. Now that I have some parts functioning properly I am in the process of migrating all the databases from mongodb to postgres (I used to hate sql and mongodb was easy to use, but Im starting to realise sql is quite useful in the current use case). Now the tables are all set up, but I am not sure what package to use in the backend code, mainly Psycopg3 or SQLalchemy. I know SQL and can write it easily, but the abstractions with SQLalchemy might give additional security features with the way it works, but building all the models and repos will also be a pain in the ass lol.\n\nDoes anyone have experience or recommendations on which to use?"}
{"instruction": "Is anyone playing with face matching using Python?", "input": "", "output": "Is anyone playing with face matching using Python?\nOkay, here's a quick question for Python experts.\n\nI was reading some articles about face recognition and image matching technology when I stumbled upon this program named FaceSeek which matches faces in pictures all over the Internet.\n\nI'm not sure what stacks they use, but it piqued my interest regarding the Python side.\n\nLike, are folks here working with Python libs on face embeddings, similarity searches, and large image datasets?\n\nI had a little experience with OpenCV and some machine learning libraries in the past, but this kind of scale feels like the next level. Also curious how the tradeoff between accuracy and FP is managed for actual applications. They're not pushing any products but are just interested in how Python programmers would solve face recognition tasks. If you are interested in this field, you are likely to google FaceSeek or something similar anyway. Would be great to hear what libraries people actually use."}
{"instruction": "I built a dev blog! First deep dive: How Ruff and UV changed my mind about Python setups.", "input": "", "output": "I built a dev blog! First deep dive: How Ruff and UV changed my mind about Python setups.\nI’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.\n\nI built [https://gburek.dev](https://gburek.dev) from scratch using Next.js + Cloudflare Workers for that sweet serverless setup. I also made it fully bilingual (EN/PL).\n\nMy 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!\n\nAnyway, the main reason I’m posting is to share the first \"serious\" article I cooked up:\n\nWhy I use UV and Ruff in Python projects, and you should too - [https://gburek.dev/en/blog/why-i-use-ruff](https://gburek.dev/en/blog/why-i-use-ruff)\n\nI 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.\n\nWe'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!"}
{"instruction": "Comparing Python Type Checkers: Speed and Memory", "input": "", "output": "Comparing Python Type Checkers: Speed and Memory\nIn our latest type checker comparison blog we cover the speed and memory benchmarks we run regularly across 53 popular open source Python packages. This includes results from a recent run, comparing Pyrefly, Ty, Pyright, and Mypy, although exact results change over time as packages release new versions.\n\nThe results from the latest run: Rust-based checkers are roughly an order of magnitude faster, with Pyrefly checking pandas in 1.9 seconds vs. Pyright's 144.\n\n[https://pyrefly.org/blog/speed-and-memory-comparison/](https://pyrefly.org/blog/speed-and-memory-comparison/)"}
{"instruction": "Convert your bear images into bear images: Bear Right Back", "input": "", "output": "Convert your bear images into bear images: Bear Right Back\n# What My Project Does\n\n**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**.\n\nNo 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.\n\nrepo: [https://github.com/JoshuaKasa/bearrb](https://github.com/JoshuaKasa/bearrb)\n\n# Target Audience\n\nThis is obviously a **toy / experimental project**, not meant for production image editing.\n\nIt's mainly for:\n\n* people interested in algorithmic image processing\n* optimization under hard constraints\n* weird/fun CLI tools\n* math-y or computational art experiments\n\n# Comparison\n\nMost image tools try to be useful and correct... bearrb does not.\n\nInstead 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**"}
{"instruction": "Anyone running FastAPI in production with high traffic? How has your experience been?", "input": "", "output": "Anyone running FastAPI in production with high traffic? How has your experience been?\nQuick 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?"}
{"instruction": "PyNote: A zero-setup, serverless Python notebook environment that runs entirely in the browser", "input": "", "output": "PyNote: A zero-setup, serverless Python notebook environment that runs entirely in the browser\n# PyNote\n\n[Live Tutorial](https://pynote-notebook.vercel.app/?open=tutorial)  |  [GitHub](https://github.com/bouzidanas/pynote-notebook-editor)\n\n# What my project does\n\n**PyNote** is a serverless, zero-setup Python notebook environment that runs entirely in your web browser using WebAssembly (Pyodide). It removes the need for backend kernels or cloud infrastructure, ensuring all code executes locally on your machine for privacy and speed. It features a custom UI python module(`pynote_ui`) that allows Python code to render native, interactive web components (like sliders, buttons, and layouts) and high-performance visualizations directly in the notebook output.\n\nTruth be told, nothing above is special. Many existing open-source notebook environments do this and more.\n\n# What I think makes PyNote special\n\n1. **Modern tech stack** (what its built with):\n\n* SolidJS for reactive javascript framework (fine-grained reactivity and performance)\n* Pyodide for running the Python interpreter and scientific stack (NumPy, Pandas) directly in the browser\n* DaisyUI for modern, accessible, and *themeable* UI components based on Tailwind CSS.\n* Tailwind CSS for consistent, responsive styling/theming\n* CodeMirror for a robust, IDE-grade code editors\n* Milkdown for a powerful WYSIWYG Markdown editors\n* Observable Plot for a lightweight, capable, and declarative charting library (perfect for SolidJS)\n\n1. **Built for presentation!** This is the main thing.\n\nPyNote isn't trying to replace heavy-duty compute environments. If you're training large machine learning models, you need a GPU and a real server.\n\nBut where PyNote aims to excel is ***presentation***. The UI is built with [daisyUI](https://daisyui.com/) a component library for Tailwind CSS that provides semantic class names and a ***powerful theming system***. This gives us consistent, polished components out of the box while keeping everything customizable. You can adjust the following for the whole notebook:\n\n* Colors (background, foreground, primary, secondary, accent, H1-4, and more), fonts, and spacing (line, block, header, cell, and more)\n* **Section-scoped styling** where everything under the same heading shares theme elements\n\nThe goal: notebooks that look good enough to publish, share, present, and use in blogs, documentation, and articles. When file export features are completed, you'll be able to save stripped-down versions of your notebooks as standalone mini-apps to embed in websites, blogs, or documentation. There will also be other export options like python and markdown.\n\n3. Has a lot of cool features:\n\n* **Marimo-style reactive mode!** There are plans to actually add greater reactivity soon (in testing).\n* **3 other execution modes!** Sequential, Hybrid, Concurrent\n* Theme is entirely customizable (or will be when release) and can be applied app-wide, session-only, or even stored into the notebook metadata itself so the notebook carries its presentation/look with it.\n* Presentation mode\n* Session persistence. Even if you close your tab, you wont lose your progress. You can set app theme, execution mode, and code visibility options as well as other options to apply to the session only.\n\n# Open source release\n\nWhen this app is ready for release, it will be open sourced. Right now it is not.. It is about 70% there. But it is [public](https://github.com/bouzidanas/pynote-notebook-editor) and [live"}
{"instruction": "If you're working with data pipelines, these repos are very useful", "input": "", "output": "If you're working with data pipelines, these repos are very useful\n#\n\n[ibis](https://github.com/ibis-project/ibis)\nA Python API that lets you write queries once and run them across multiple data backends like DuckDB, BigQuery, and Snowflake.\n\n[pygwalker](https://github.com/Kanaries/pygwalker)\nTurns a dataframe into an interactive visual exploration UI instantly.\n\n[katana](https://github.com/projectdiscovery/katana)\nA fast and scalable web crawler often used for security testing and large-scale data discovery."}
{"instruction": "I built a wrapper to get unlimited free access to GPT-4o, Gemini 2.5, and Llama 3 (16k+ reqs/day)", "input": "", "output": "I built a wrapper to get unlimited free access to GPT-4o, Gemini 2.5, and Llama 3 (16k+ reqs/day)\nHey everyone!\n\n\nI built FreeFlow LLM because I was tired of hitting rate limits on free tiers and didn't want to manage complex logic to switch between providers for my side projects.\n\n\nWhat My Project Does\nFreeFlow is a Python package that aggregates multiple free-tier AI APIs (Groq, Google Gemini, GitHub Models) into a single, unified interface. It acts as an intelligent proxy that:\n1. Rotates Keys: Automatically cycles through your provided API keys to maximize rate limits.\n2. Auto-Fallbacks: If one provider (e.g., Groq) is exhausted or down, it seamlessly switches to the next available one (e.g., Gemini).\n3. Unifies Syntax: You use one simple client.chat() method, and it handles the specific formatting for each provider behind the scenes.\n4. Supports Streaming: Full support for token streaming for chat applications.\n\n\nTarget Audience\nThis tool is meant for developers, students, and researchers who are building MVPs, prototypes, or hobby projects.\n\\- Production? It is not recommended for mission-critical production workloads (yet), as it relies on free tiers which can be unpredictable.\n\\- Perfect for: Hackathons, testing different models (GPT-4o vs Llama 3), and running personal AI assistants without a credit card.\n\n\nComparison\nThere are other libraries like LiteLLM or LangChain that unify API syntax, but FreeFlow differs in its focus on \"Free Tier Optimization\".\n\\- vs LiteLLM/LangChain: Those libraries are great for connecting to any provider, but you still hit rate limits on a single key immediately. FreeFlow is specifically architected to handle multiple keys and multiple providers as a single pool of resources to maximize uptime for free users.\n\\- vs Manual Implementation: Writing your own try/except loops to switch from Groq to Gemini is tedious and messy. FreeFlow handles the context management, session closing, and error handling for you.\n\n\nExample Usage:\n\n`pip install freeflow-llm`\n\n    # Automatically uses keys from your environment variables\n    with FreeFlowClient() as client:\n        response = client.chat(\n            messages=[{\"role\": \"user\", \"content\": \"Explain quantum computing\"}]\n        )\n        print(response.content)\n\n\nLinks\n\\- Source Code: [https://github.com/thesecondchance/freeflow-llm](https://github.com/thesecondchance/freeflow-llm)\n\\- Documentation: [http://freeflow-llm.joshsparks.dev/docs](http://freeflow-llm.joshsparks.dev/docs)\n\\- PyPI: [https://pypi.org/project/freeflow-llm/](https://pypi.org/project/freeflow-llm/)\n\n\nIt's MIT Licensed and open source. I'd love to hear your thoughts!from freeflow\\_llm import FreeFlowClient"}
{"instruction": "Designing a Python Language Server: Lessons from Pyre that Shaped Pyrefly", "input": "", "output": "Designing a Python Language Server: Lessons from Pyre that Shaped Pyrefly\n[Pyrefly](https://github.com/facebook/pyrefly) is a next-generation Python type checker and language server, designed to be extremely fast and featuring advanced refactoring and type inference capabilities.\n\nPyrefly is a spiritual successor to [Pyre](https://pyre-check.org/), the previous Python type checker developed by the same team. The differences between the two type checkers go far beyond a simple rewrite from OCaml to Rust - we designed Pyrefly from the ground up, with a completely different architecture.\n\nPyrefly’s design comes directly from our experience with Pyre. Some things worked well at scale, while others did not. After running a type checker on massive Python codebases for a long time, we got a clearer sense of which trade-offs actually mattered to users.\n\nThis post is a write-up of a few lessons from Pyre that influenced how we approached Pyrefly.\n\nLink to full blog: https://pyrefly.org/blog/lessons-from-pyre/\n\nThe outline of topics is provided below that way you can decide if it's worth your time to read :)\n- Language-server-first Architecture\n- OCaml vs. Rust\n- Irreversible AST Lowering\n- Soundness vs. Usability\n- Caching Cyclic Data Dependencies"}
{"instruction": "Someone hijacked MemoryOS PyPI releases by replacing the build backend", "input": "", "output": "Someone hijacked MemoryOS PyPI releases by replacing the build backend\nThe attacker swapped in a custom `pyproject.toml` build backend that grabbed the PyPI token before the real upload ran. Then used that token to push the backdoored package themselves.\n\ncomplete - [safedep.io/memtensor-sckit-worm-npm-pypi](http://safedep.io/memtensor-sckit-worm-npm-pypi)"}
{"instruction": "Fast, exact K-nearest-neighbour search for Python", "input": "", "output": "Fast, exact K-nearest-neighbour search for Python\nPyNear is a Python library with a C++ core for exact or approximate (fast) KNN search over metric spaces. It is built around Vantage Point Trees, a metric tree that scales well to higher dimensionalities where kd-trees degrade, and uses SIMD intrinsics (AVX2 on x86-64, portable fallbacks on arm64/Apple Silicon) to accelerate the hot distance computation paths.\n\nHeres a comparison between several other widely used KNN libraries: https://github.com/pablocael/pynear/blob/main/README.md#why-pynear\n\nHeres a benchmark comparison: https://github.com/pablocael/pynear/blob/main/pynear/benchmark/README.md\n\nMain page: https://github.com/pablocael/pynear"}
{"instruction": "4 Pyrefly Type Narrowing Patterns that make Type Checking more Intuitive", "input": "", "output": "4 Pyrefly Type Narrowing Patterns that make Type Checking more Intuitive\nSince Python is a duck-typed language, programs often narrow types by checking a structural property of something rather than just its class name. For a type checker, understanding a wide variety of narrowing patterns is essential for making it as easy as possible for users to type check their code and reduce the amount of changes made purely to “satisfy the type checker”.\n\nIn this blog post, we’ll go over some cool forms of narrowing that Pyrefly supports, which allows it to understand common code patterns in Python.\n\nTo the best of our knowledge, Pyrefly is the only type checker for Python that supports all of these patterns.\n\nContents:\n1. hasattr/getattr\n2. tagged unions\n3. tuple length checks\n4. saving conditions in variables\n\nBlog post: https://pyrefly.org/blog/type-narrowing/\nGithub: https://github.com/facebook/pyrefly"}
{"instruction": "Ruff + Ty vs Ruff + Pyrefly — which type checking stack makes more sense in 2026?", "input": "", "output": "Ruff + Ty vs Ruff + Pyrefly — which type checking stack makes more sense in 2026?\nI’m trying to decide between two Python tooling stacks:\n\n* **Ruff + Ty**\n* **Ruff + Pyrefly**\n\nCurious what people are using in practice.\n\n* When does Pyrefly become worth the extra complexity?\n* Is Ty “enough” for most real-world projects?\n* Are they solving fundamentally different problems?"}
{"instruction": "The Future of Python: Evolution or Succession — Brett Slatkin - PyCascades 2026", "input": "", "output": "The Future of Python: Evolution or Succession — Brett Slatkin - PyCascades 2026\nhttps://www.youtube.com/watch?v=1gjLPVUkZnc\n\n> A decade from now there's a reasonable chance that Python won't be the world's most popular programming language. Many languages eventually have a successor that inherits large portions of its technical momentum and community contributions. With Python turning 35 years old, the time could be ripe for Python's eventual successor to emerge. How can we help the Python community navigate this risk by embracing change and evolving, or influencing a potential successor language?\n\n> This talk covers the past, present, and future of the Python language's growing edge. We'll learn about where Python began and its early influences. We'll look at shortcomings in the language, how the community is trying to overcome them, and opportunities for further improvement. We'll consider the practicalities of language evolution, how other languages have made the shift, and the unique approaches that are possible today (e.g., with tooling and AI)."}
{"instruction": "What’s a low memory way to run a Python http endpoint?", "input": "", "output": "What’s a low memory way to run a Python http endpoint?\nI have a simple process that has a single endpoint that needs exposing on http. Nothing fancy but need to run it in a container using minimal memory. Currently running with uvicorn which needs \\~600Mb of ram on start up. This seems crazy.\n\nI have also tried Grainian which seems similar usage.\n\nFor perspective a Nodejs container uses 128mb, and a full phpmyadmin uses 20!\n\nI realise you shouldn’t compare but a 30x increase in memory is not a trivial matter with current ram pricing!"}
{"instruction": "Async/Await is a Plague: Part 1 Roots", "input": "", "output": "Async/Await is a Plague: Part 1 Roots\nThis is part 1 of series of blog posts that explains why `async/await` is not suitable concurrency pattern most of the time and what other alternative concurrency models we can use instead.\nThe codes and example are in Python in this first part we will look at the roots of async/await and build an event loop using generators from ground up:\n\n[https://theblog.info/posts/asyncawait-is-a-plague-part-1-roots](https://theblog.info/posts/asyncawait-is-a-plague-part-1-roots)"}
{"instruction": "Python Typing Survey 2025: Code Quality and Flexibility As Top Reasons for Typing Adoption", "input": "", "output": "Python Typing Survey 2025: Code Quality and Flexibility As Top Reasons for Typing Adoption\nThe 2025 Typed Python Survey, conducted by contributors from JetBrains, Meta, and the broader Python typing community, offers a comprehensive look at the current state of Python’s type system and developer tooling.\n\nThe survey captures the evolving sentiment, challenges, and opportunities around Python typing in the open-source ecosystem.\n\nIn this blog we’ll cover a summary of the key findings and trends from this year’s results.\n\n[LINK](https://engineering.fb.com/2025/12/22/developer-tools/python-typing-survey-2025-code-quality-flexibility-typing-adoption/)"}
{"instruction": "What do you love and dislike the most about Python? (beginners and long-time devs)", "input": "", "output": "What do you love and dislike the most about Python? (beginners and long-time devs)\nHi! 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.\n\nSo what features do you really cherish and what problems/limitations really frustrate you?\n\nI'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.\n\nThanks for your time!"}
{"instruction": "Tortoise ORM 1.0 release (with migrations support)", "input": "", "output": "Tortoise ORM 1.0 release (with migrations support)\nIf you’re a Python web developer, there’s a chance you’ve come across this ORM before. But there’s also a good chance you passed it by - because it was missing some functionality you needed.\n\nProbably the most requested feature that held many people back and pushed them to use Alembic together with SQLAlchemy was full-fledged migrations support.\n\nTortoise did have migrations support via the Aerich library, but it came with a number of limitations: you had to connect to the database to generate migrations, migrations were written in raw SQL, and the overall coupling between the two libraries was somewhat fragile - which didn’t feel like a robust, reliable system.\n\nThe new release includes a lot of additions and fixes, but I’d highlight two that are most important to me personally:\n\n* Built-in migrations, with automatic change detection in offline mode, and support for data migrations via RunPython and RunSQL.\n* Convenient support for custom SQL queries using PyPika (the query builder that underpins Tortoise) and execute\\_pypika, including returning typed objects as results.\n\nThanks to this combination of new features, Tortoise ORM can be useful even if you don’t want to use it as an ORM: it offers an integrated migrations system (in my view, much more convenient and intuitive than Alembic) and a query builder, with minimal additional dependencies and requirements for your architecture.\n\nRead the changelog, try Tortoise in your projects, and contribute to the project by creating issues and PRs.\n\n\nP.s. not sure I wouldn't be auto-banned for posting links, so you can find library at:\n\n{github}/tortoise/tortoise-orm"}
{"instruction": "Getting distracted constantly while coding looking for advice", "input": "", "output": "Getting distracted constantly while coding looking for advice\nI genuinely want to code and build stuff, but I keep messing this up.\n\nI’ll sit down to code, start fine… and then 10–15 minutes later I’m googling random things, opening YouTube “for a quick break,” or scrolling something completely unrelated. Next thing I know, an hour is gone and I feel bored + annoyed at myself.\n\nIt’s not that I hate coding once I’m *in the flow*, I enjoy it. The problem is **staying focused long enough to reach that point**.\n\nFor people who code regularly:\n\n* How do you stop jumping to random tabs?\n* Do you force discipline or use some system?\n* Is this just a beginner problem or something everyone deals with?\n\nWould love practical advice\n\n\nThanks."}
{"instruction": "Free Python books that authors intentionally made available", "input": "", "output": "Free Python books that authors intentionally made available\nI maintain a small curated [list of Python books](https://www.pythonkitchen.com/legally-free-python-books-list/) that are legally free to read. These are books where the author or publisher explicitly chose to make the full content available at no cost.\n\nI recently updated the list with a few newer additions and wanted to share it in case it’s useful to others here.\n\nThere are no pirated or scraped materials included. Every book links to an official source provided by the author or publisher."}
{"instruction": "Using the walrus operator := to self-document if conditions", "input": "", "output": "Using the walrus operator := to self-document if conditions\nRecently I have been using the walrus operator `:=` to document if conditions.\n\nSo instead of doing:\n\n    complex_condition = (A and B) or C\n    if complex_condition:\n        ...\n\nI would do:\n\n    if complex_condition := (A and B) or C:\n        ...\n\nTo me, it reads better. However, you could argue that the variable `complex_condition` is unused, which is therefore not a good practice. Another option would be to extract the condition computing into a function of its own. But I feel it's a bit overkill sometimes.\n\nWhat do you think ?"}
{"instruction": "PySimpleGUI 6 is LGPL again", "input": "", "output": "PySimpleGUI 6 is LGPL again\nLooks like the commercialisation of PySimpleGUI has come to an end.\n\n>PySimpleGUI 6 - Back to LGPL3\nhttps://github.com/PySimpleGUI/PySimpleGUI"}
{"instruction": "Polars and the ecosystem", "input": "", "output": "Polars and the ecosystem\nFor polars users: How viable is to avoid pandas and pyarrow dependencies when you need to interact with popular visualization and statistics packages?\n\nSome dependencies still have `import pandas` here and there, sometimes for no good reason; at least this doesn't require pyarrow. But some other ones do the `df.to_pandas()` conversion internally, which requires pyarrow too.\n\nIn many cases this can be prevented by going bare numpy, or creating a pandas df from numpy columns, which is no big deal. This frequently would be zero-copy for numeric types if there are no NAs involved.\n\nWhat has been you experience in this regard?"}
{"instruction": "How to print \"Hello World\" in python", "input": "", "output": "How to print \"Hello World\" in python\n    from abc import ABC, abstractmethod\n\n    class AbstractGreetingFactory(ABC):\n\n        def create_pipeline(self):\n            pass\n\n    class ConcreteGreetingFactory(AbstractGreetingFactory):\n        def create_pipeline(self):\n            return GreetingPipeline([\n                CharacterSource(),\n                CharacterAssembler(),\n                EncodingLayer(),\n                OutputDispatcher()\n            ])\n\n    class CharacterSource:\n        def get_data(self):\n            return [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n\n    class CharacterAssembler:\n        def process(self, data):\n            return ''.join(map(chr, data))\n\n    class EncodingLayer:\n        def process(self, data):\n            return data.encode('utf-8').decode('utf-8')\n\n    class OutputDispatcher:\n        def process(self, data):\n            Executor().execute(lambda: print(data))\n            return data\n\n    class GreetingPipeline:\n        def __init__(self, stages):\n            self.stages = stages\n\n        def run(self):\n            data = None\n            for stage in self.stages:\n                if hasattr(stage, \"get_data\"):\n                    data = stage.get_data()\n                else:\n                    data = stage.process(data)\n            return data\n\n    class Executor:\n        def execute(self, func):\n            return self._deep_execute(func)\n\n        def _deep_execute(self, func):\n            return func()\n\n    class GreetingApplication:\n        def __init__(self, factory: AbstractGreetingFactory):\n            self.pipeline = factory.create_pipeline()\n\n        def start(self):\n            return self.pipeline.run()\n\n    if __name__ == \"__main__\":\n        app = GreetingApplication(ConcreteGreetingFactory())\n        app.start()"}
{"instruction": "Introducing Expanse: a modern and elegant web application framework", "input": "", "output": "Introducing Expanse: a modern and elegant web application framework\nAfter months of working on it on and off since I retired from the maintenance of Poetry, I am pleased to unveil my new project: Expanse, a **modern** and **elegant** web application framework.\n\n## What my project does?\n\nExpanse is a new web application framework with, at the heart of its design and architecture, a strong focus on **developer experience**\n\nExpanse wants to get out of your way and let you build what matters by giving you intuitive and powerful tools like transparent **dependency injection**, a **powerful database component** (powered by [SQLAlchemy](https://www.sqlalchemy.org/)), **queues** (*Coming soon*), **authentication** (*Coming soon*), **authorization** (*Coming soon*), and more.\n\nIt’s inspired by frameworks from other languages like Laravel in PHP or Rails in Ruby, and aims at being a batteries included framework that gives you all the tools you might need so you can focus on your business logic without having to sweat out every detail or reinventing the wheel.\n\nYou can check out the [repository](https://github.com/expanse-framework/expanse) or the [website](https://expanse-framework.com/) to learn more about the project and it’s concepts.\n\nWhile it aims at being a batteries-included framework, some batteries are still missing but are planned in the Roadmap to the 1.0 version:\n\n- A queue/jobs system with support for multiple backends\n- Authentication/Authorization\n- Websockets\n- Logging management\n- and more\n\n## Target audience\n\nAnyone unsatisfied with existing Python web frameworks or curious to try out a different and, hopefully, more intuitive way to build web applications.\n\nIt’s still early stage though, so any feedback and beta testers are welcome, but it is functional and the project’s website itself runs on Expanse to test it in normal conditions.\n\n## Comparison\n\nI did not do any automated performance benchmarks that I can share here yet but did some simple benchmarks on my end that showed Expanse slightly faster than FastAPI and on par with Litestar. However, don’t take my word for it since benchmarks are not always a good measure of real world use cases, so it’s best for you to make your own and judge from there.\n\nFeature-wise, it’s hard to make a feature by feature comparison since some are still missing in Expanse compared to other frameworks (but the gap is closing) while some features are native to Expanse and does not exist in other frameworks ([encryption](https://expanse-framework.com/docs/security/encryption) for example). Expanse also has its own twists on expected features from any modern framework ([dependency injection](https://expanse-framework.com/docs/architecture/dependency-injection), [pagination](https://expanse-framework.com/docs/database/pagination) or [OpenAPI documentation](https://expanse-framework.com/docs/features/openapi)).\n\n## Why I built Expanse?\n\nWhile working on Python web applications, personally or professionally, I grew frustrated with existing frameworks that felt incomplete or disjointed when scaling up.\n\nSo I set out to build a framework that is aligned with what I envisioned a robust framework should look like, drawing inspiration from other frameworks in other languages that I liked from a developer experience standpoint.\n\nAnd this was the occasion for me to step out of an open source burn-out and start a new motivating project with which I could learn more about the intricacies of building a web fram"}
{"instruction": "Polars vs Pandas in 2025 — have you fully migrated yet?", "input": "", "output": "Polars vs Pandas in 2025 — have you fully migrated yet?\nBeen using Polars for about a year now. The performance gap is undeniable, but I still see most tutorials and libraries defaulting to Pandas.\n\nCurious about the community's current state:\n\n\\- Have you fully migrated to Polars?\n\n\\- What's blocking adoption for you?\n\n\\- Any libraries you wish had native Polars support?\n\nFor me, the lazy evaluation and query optimization alone made switching worth it. But ecosystem compatibility is still a pain point."}
{"instruction": "2026 Python Type System and Tooling Survey", "input": "", "output": "2026 Python Type System and Tooling Survey\n\nThis 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).\n\nYour responses will help us identify common blockers, improve tooling/resources, and enhance the overall experience of using Python's type system.\n\nEven if you have never actively used type hints in your code, your thoughts are still valuable and we want to hear from you.\n\nThe survey should take approximately 5-10 minutes to complete.\n\n**Please take the survey [HERE](https://surveymonkey.com/r/python_typing) and share it with your friends or colleagues.**\n\nIf you're interested in the results for last year's survey, see [this post](https://www.reddit.com/r/Python/comments/1q7cyz4/python_typing_survey_2025_code_quality_and/).\n\n^(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](https://x.com/ThePSF/status/2085076607719375200). I have permission from the mods to post this under the \"News\" flair)"}
{"instruction": "I built bytes.replace() for CUDA - process multi-GB files without leaving the GPU", "input": "", "output": "I built bytes.replace() for CUDA - process multi-GB files without leaving the GPU\nBuilt a CUDA kernel that does Python's `bytes.replace()` on the GPU without CPU transfers.\n\n**Performance (RTX 3090):**\n\n    Benchmark                      | Size       | CPU (ms)     | GPU (ms)   | Speedup\n    -----------------------------------------------------------------------------------\n    Dense/Small (1MB)              | 1.0 MB     |   3.03       |   2.79     |  1.09x\n    Expansion (5MB, 2x growth)     | 5.0 MB     |  22.08       |  12.28     |  1.80x\n    Large/Dense (50MB)             | 50.0 MB    | 192.64       |  56.16     |  3.43x\n    Huge/Sparse (100MB)            | 100.0 MB   | 492.07       | 112.70     |  4.37x\n\n    Average: 3.45x faster | 0.79 GB/s throughput\n\n**Features:**\n\n* Exact Python semantics (leftmost, non-overlapping)\n* Streaming mode for files larger than GPU memory\n* Session API for chained replacements\n* Thread-safe\n\n**Example:**\n\npython\n\n    from cuda_replace_wrapper import CudaReplaceLib\n\n    lib = CudaReplaceLib('./cuda_replace.dll')\n    result = lib.unified(data, b\"pattern\", b\"replacement\")\n\n    # Or streaming for huge files\n    cleaned = gpu_replace_streaming(lib, huge_data, pairs, chunk_bytes=256*1024*1024)\n\nBuilt this for a custom compression algorithm. Includes Python wrapper, benchmark suite, and pre-built binaries.\n\nGitHub: [https://github.com/RAZZULLIX/cuda\\_replace](https://github.com/RAZZULLIX/cuda_replace)"}
{"instruction": "Is dropping support for Python versions 3.8 and 3.9 a breaking change?", "input": "", "output": "Is dropping support for Python versions 3.8 and 3.9 a breaking change?\nI am the maintainer of the Python tools for the Polylith Architecture. The main use case is for Microservices in Monorepos, and being able to share code between them in a Developer and Agent-friendly way.\n\nToday, I can see that some Polylith users are running Python versions 3.8 (few) and 3.9 (some) according to the download stats.\n\nDropping these versions would be mostly a convenience: then I can implement PEP 621 internally, and bump subdependencies. It's not an urgent task, but something that I probably should do during 2026.\n\nThe Polylith project is releasing new versions according to semantic versioning, and dropping support would probably be a Breaking feature - even if the Python versions themselves are unsupported since quite a while. I hesitate how to approach this, because I don't want to cause disruptions in the flow of the Developer Teams out there.\n\nI know that the \"big\" tools in the Python community handle this in different ways. Such as FastAPI and Typer, dropping 3.8 and 3.9 support without a Major version change (I guess they don't use semantic versioning?).\n\nBumping the Major version could make teams miss out on new versions if they pin the tool to the current version. I also know how I usually react to a new Major version for tools I use on a daily basis:\n\n\"What do we need to change on our end to make this new version of the library/tool work?\"\n\nBumping the minor version would break the builds for those running on Python 3.8 and 3.9 users, unless they already pin the tool to a specific version.\n\nWhat would be the best way to go forward here?"}
{"instruction": "I built a pre-commit linter that catches AI-generated code patterns", "input": "", "output": "I built a pre-commit linter that catches AI-generated code patterns\n# What My Project Does\n\n**grain** is a pre-commit linter that catches code patterns commonly produced by AI code generators. It runs before your commit and flags things like:\n\n* **NAKED\\_EXCEPT** \\-- bare `except: pass` that silently swallows errors (156 instances in my own codebase)\n* **HEDGE\\_WORD** \\-- docstrings full of \"robust\", \"comprehensive\", \"seamlessly\"\n* **ECHO\\_COMMENT** \\-- comments that restate what the code already says\n* **DOCSTRING\\_ECHO** \\-- docstrings that expand the function name into a sentence and add nothing\n\nI ran it on my own AI-assisted codebase and found 184 violations across 72 files. The dominant pattern was exception handlers that caught hardware failures, logged them, and moved on -- meaning the runtime had no idea sensors stopped working.\n\n# Target Audience\n\nAnyone using AI code generation (Copilot, Claude, ChatGPT, etc.) in Python projects and wants to catch the quality patterns that slip through existing linters. This is not a toy -- I built it because I needed it for a production hardware abstraction layer where autonomous agents are regular contributors.\n\n# Comparison\n\nExisting linters (pylint, ruff, flake8) catch syntax, style, and type issues. They don't catch AI-specific patterns like docstring padding, hedge words, or the tendency of AI generators to wrap everything in try/except and swallow the error. grain fills that gap. It's complementary to your existing linter, not a replacement.\n\n# Install\n\n    pip install grain-lint\n\nPre-commit compatible. Configurable via `.grain.toml`. Python only (for now).\n\n**Source:** [github.com/mmartoccia/grain](https://github.com/mmartoccia/grain)\n\nHappy to answer questions about the rules, false positive rates, or how it compares to semgrep custom rules."}
{"instruction": "Application layer security for FastAPI and Flask", "input": "", "output": "Application layer security for FastAPI and Flask\nI've been maintaining fastapi-guard for a while now. It sits between the internet and your FastAPI endpoints and inspects every request before it reaches your code. Injection detection, rate limiting, geo-blocking, cloud IP filtering, behavioral analysis, 17 checks total.\n\nA few weeks ago I came across this TikTok post where a guy ran OpenClaw on his home server, checked his logs after a couple weeks. 11,000 attacks in 24 hours. Chinese IPs, Baidu crawlers, DigitalOcean scanners, path traversal probes, brute force sequences. I commented \"I don't understand why people won't use FastAPI Guard\" and the thread kind of took off from there. Someone even said \"a layer 7 firewall, very important with the whole new era of AI and APIs.\" (they understood the assignment) broke down the whole library in the replies. I was truly proud to see how in depth some devs went...\n\nBut that's not why I'm posting. I felt like FastAPI was falling short. Flask still powers a huge chunk of production APIs and most of them have zero request-level security beyond whatever nginx is doing upstream, or whatever fail2ban fails to ban... So I built flaskapi-guard (and that's the v1.0.0 I just shipped) as the homologue of fastapi-guard. Same features, same functionalities. Different framework.\n\nIt's basically a Flask extension that hooks into `before_request` and `after_request`, not WSGI middleware. That's because WSGI middleware fires before Flask's routing, so it can't access route config, decorator metadata, or `url_rule`. The extension pattern gives you full routing context, which is what makes per-route security decorators possible.\n\n```python\nfrom flask import Flask\nfrom flaskapi_guard import FlaskAPIGuard, SecurityConfig\n\napp = Flask(__name__)\nconfig = SecurityConfig(rate_limit=100, rate_limit_window=60)\nFlaskAPIGuard(app, config=config)\n```\n\nAnd so that's it. Done. 17 checks on every request.\n\nThe whole pipeline will catch: XSS, SQL injection, command injection, path traversal, SSRF, XXE, LDAP injection, code injection (including obfuscation detection and high-entropy payload analysis). On top of that: rate limiting with auto-ban, geo-blocking, cloud provider IP blocking, user agent filtering, OWASP security headers. Those 5,697 Chinese IPs from the TikTok? `blocked_countries=[\"CN\"]`. Done. Baidu crawlers? `blocked_user_agents=[\"Baiduspider\"]`. The DigitalOcean bot farm? `block_cloud_providers={\"AWS\", \"GCP\", \"Azure\"}`. Brute force? `auto_ban_threshold=10` and the IP is gone after 10 violations. Path traversal probes for `.env` and `/etc/passwd`? Detection engine catches those automatically, zero config.\n\nThe decorator system is what separates this from static nginx rules:\n\n```python\nfrom flaskapi_guard import SecurityDecorator\n\nsecurity = SecurityDecorator(config)\n\n.route(\"/api/admin/sensitive\", methods=[\"POST\"])\n.require_https()\n.require_auth(type=\"bearer\")\n.require_ip(whitelist=[\"[IP]/8\"])\n.rate_limit(requests=5, window=3600)\nu/security.block_countries([\"CN\", \"RU\", \"KP\"])\ndef admin_endpoint():\n    return {\"status\": \"admin action\"}\n```\n\nPer-route rate limits, auth requirements, geo-blocking, all stacked as decorators on the function they protect. Try doing that in nginx.\n\nPeople have been using fastapi-guard for things I didn't even think of when I first built it. Startups building in stealth with remote-first teams, public facing API but whitelisted so only their devs can reach it. Nobody else even knows the"}
{"instruction": "TIL: Facebook's Cinder is now a standalone CPython extension", "input": "", "output": "TIL: Facebook's Cinder is now a standalone CPython extension\nJust came across **CinderX** today and realized it’s evolved past the old Cinder fork.\n\nFor those who missed it, it’s Meta’s internal high-performance Python runtime, but it’s now being built as a **standalone extension** for CPython. It includes their JIT and 'Static Python' compiler.\n\nIt targets 3.14 or later.\n\n**Repo:** [https://github.com/facebookincubator/cinderx]()"}
{"instruction": "Robyn (finally) offers first party Pydantic integration 🎉", "input": "", "output": "Robyn (finally) offers first party Pydantic integration 🎉\nFor the unaware - [Robyn](https://github.com/sparckles/Robyn) is a fast, async Python web framework built on a Rust runtime.\n\nPydantic integration is probably one of the most requested feature for us. Now we have it :D\n\nWanted to share it with people outside the Robyn community\n\nYou can check out the release at - [https://github.com/sparckles/Robyn/releases/tag/v0.81.0](https://github.com/sparckles/Robyn/releases/tag/v0.81.0)"}
{"instruction": "WebRockets: High-performance WebSocket server for Python, powered by Rust", "input": "", "output": "WebRockets: High-performance WebSocket server for Python, powered by Rust\n**What My Project Does**\n\nWebRockets is a WebSocket library with its core implemented in Rust for maximum performance. It provides a clean, decorator-based API that feels native to Python.\n\n**Features**\n\n* Rust core - High throughput, low latency\n* Django integration - Autodiscovery, management commands, session auth out of the box\n* Pattern matching - Route messages based on JSON field values\n* Pydantic validation - Optional schema validation for payloads\n* Broadcasting - Built-in Redis and RabbitMQ support for multi-server setups\n* Sync and Async - Works with both sync and async Python callbacks\n\n**Target Audience**\n\nFor developers who need WebSocket performance without leaving the Python ecosystem, or those who want a cleaner, more flexible API than existing solutions.\n\n**Comparison**\n\nBenchmarks show significant performance gains over pure-Python WebSocket libraries. The API is decorator-based, similar to FastAPI routing patterns.\n\n**Why I Built This**\n\nI needed WebSockets for an existing Django app. Django Channels felt cumbersome, and rewriting in another language meant losing interop with existing code. WebRockets gives Rust performance while staying in Python.\n\n**Source code:** [https://github.com/ploMP4/webrockets](https://github.com/ploMP4/webrockets)\n\n**Example:**\n\n    from webrockets import WebsocketServer\n\n    server = WebsocketServer()\n    echo = server.create_route(\"ws/echo/\")\n\n    @echo.receive\n    def receive(conn, data):\n        conn.send(data)\n\n    server.start()"}
{"instruction": "Scikit-learn 1.9.1 released with Python 3.15 support", "input": "", "output": "Scikit-learn 1.9.1 released with Python 3.15 support\nScikit-learn has released [1.9.1](https://github.com/scikit-learn/scikit-learn/releases/tag/1.9.1) with full Python 3.15 support, including wheels on PyPI.\n\nNumPy and SciPy also support Python 3.15 and have wheels on PyPI. Pandas just [backported](https://github.com/pandas-dev/pandas/pull/68435) Python 3.15 support to their 3.0.x maintenance branch, and will release Pandas 3.0.6 with Python 3.15 support and wheels."}
{"instruction": "Dumb question- Why can’t Python be used to make native Android apps ?", "input": "", "output": "Dumb question- Why can’t Python be used to make native Android apps ?\nI’m a beginner when it comes to Android, so apologies if this is a dumb question.\n\nI’m trying to learn Android development, and one thing I keep wondering is why Python can’t really be used to build native Android apps, the same way Kotlin/Java are.\n\nI know there are things like Kivy or other frameworks, but from what I understand they either:\n\n* bundle a Python runtime, or\n* rely on WebViews / bridges\n\nSo here’s my probably-naive, hypothetical thought:\n\nWhat if there was a Python-like framework where you write code in a restricted subset of Python, and it *compiles* directly to native Android (APK / Dalvik / ART), without shipping Python itself?\n\nI’m guessing this is either:\n\n* impossible, or\n* impractical, or\n* already tried and abandoned\n\nBut I don’t understand where it stops.\n\nSome beginner questions I’m stuck on -\n\n* Is the problem Python’s dynamic typing?\n* Is it Android’s build tool chain?\n* Is it performance?\n* Is it interoperability with the Android SDK?\n* Or is it simply “too much work for too little benefit”?\n\nFrom an experienced perspective:\n\n* What part of this idea is fundamentally flawed?\n* At what point would such a tool become unmaintainable?\n* Why does Android more or less *force* Java/Kotlin as the source language?\n\nI’m not suggesting this should exist — I’m honestly trying to understand **why it doesn’t**.\n\nWould really appreciate explanations from people who understand Android internals, compilers, or who’ve shipped real apps"}
{"instruction": "Blog post: A different way to think about Python API Clients", "input": "", "output": "Blog post: A different way to think about Python API Clients\nHey folks. I’ve spent a lot of my hobby time recently improving a personal project.\n\nIt has helped me formalise some thoughts I have about API integrations. This is drawing from years of experience building and integrating with APIs. The issue I’ve had (mostly around the time it takes to actually get integrated), and what I think can be done about it.\n\nI am going to be working on this project through 2026. My personal goal is I want clients to feel as intentional as servers, to be treated as first-class Python code, like we do with projects such as FastAPI, Django etc.\n\nFull post here: https://paulwrites.software/articles/python-api-clients\n\nPlease share with me your thoughts!"}
{"instruction": "I built a drop-in Scikit-Learn replacement for SVD/PCA that automatically selects the optimal rank", "input": "", "output": "I built a drop-in Scikit-Learn replacement for SVD/PCA that automatically selects the optimal rank\nHi everyone,\n\nI've been working on a library called `randomized-svd` to address a couple of pain points I found with standard implementations of SVD and PCA in Python.\n\n**The Main Features:**\n\n1. **Auto-Rank Selection:** Instead of cross-validating `n_components`, I implemented the **Gavish-Donoho hard thresholding**. It analyzes the singular value spectrum and cuts off the noise tail automatically.\n2. **Virtual Centering:** It allows performing PCA (which requires centering) on **Sparse Matrices** without densifying them. It computes (X−μ)v implicitly, saving huge amounts of RAM.\n3. **Sklearn API:** It passes all `check_estimator` tests and works in Pipelines.\n\n**Why I made this:** I wanted a way to denoise images and reduce features without running expensive GridSearches.\n\n**Example:**\n\n    from randomized_svd import RandomizedSVD\n    # Finds the best rank automatically in one pass\n    rsvd = RandomizedSVD(n_components=100, rank_selection='auto')\n    X_reduced = rsvd.fit_transform(X)\n\nI'd love some feedback on the implementation or suggestions for improvements!\n\nRepo: [https://github.com/massimofedrigo/randomized-svd](https://github.com/massimofedrigo/randomized-svd)\n\nDocs: [https://massimofedrigo.com/thesis\\_eng.pdf](https://massimofedrigo.com/thesis_eng.pdf)"}
{"instruction": "What is one thing you wish you knew before distributing your first Python application?", "input": "", "output": "What is one thing you wish you knew before distributing your first Python application?\nBuilding a Python application is often the easy part. Getting it into the hands of users can introduce a completely different set of challenges.\n\nWhether it was packaging, updates, compatibility issues, licensing, documentation, or user support, many developers discover new problems only after release.\n\nLooking back, what is one thing you wish you had known before distributing your first Python application?\n\nIt would be interesting to hear the lessons people learned from real-world experience."}
{"instruction": "Benchmarking Python API frameworks with real workloads: FastAPI, Litestar, DRF, Ninja, Bolt", "input": "", "output": "Benchmarking Python API frameworks with real workloads: FastAPI, Litestar, DRF, Ninja, Bolt\nHi guys, I benchmarked the well-known (and rising star) Python API frameworks - but with real production-shaped workloads, not just raw JSON echoes. Most comparisons out there are basically \"hello world\" benchmarks, while real APIs do auth, DB access and complex queries. So this measures those, with strict resource limits and each framework's own best practices.\n\nRepo (code, full report, raw results): [https://github.com/huynguyengl99/python-api-frameworks-benchmark](https://github.com/huynguyengl99/python-api-frameworks-benchmark)\n\nThis is round 2 - last round's feedback (thanks especially to the Litestar author) directly shaped it: Litestar and Bolt now serialize with **native msgspec** instead of Pydantic (payloads byte-identical across frameworks), and everything is upgraded to latest (Django 6.0, FastAPI 0.141, Litestar 2.24, Bolt 0.10).\n\n# Setup\n\n* Each framework alone in a Docker container: 1 CPU, 750MB RAM, PostgreSQL 16\n* bombardier, 100 connections, 10s per endpoint\n* **Median over 5 separate container starts** (not best-of-N - some servers pick their throughput at startup, so best-of-N flatters the lucky ones)\n* 7 endpoints: 1KB/10KB JSON, simple DB reads, paginated articles with nested relations, article detail, and two **JWT httpOnly cookie auth** endpoints (each framework using its own ecosystem's auth library: AuthX, drf-auth-kit, django-ninja-jwt, or built-in support)\n\n# Key results (RPS)\n\n(Images aren't allowed here - all graphs are in the repo README: [https://github.com/huynguyengl99/python-api-frameworks-benchmark](https://github.com/huynguyengl99/python-api-frameworks-benchmark))\n\n|Config|json-1k|/db|/articles|/auth/me|/auth/articles|\n|:-|:-|:-|:-|:-|:-|\n|bolt|**38,576**|**1,986**|208|**3,024**|196|\n|litestar-uvicorn|31,284|1,039|246|976|193|\n|litestar-granian|19,006|1,180|**250**|1,104|**210**|\n|fastapi-uvicorn|13,845|984|224|820|193|\n|drf-gunicorn|3,925|282|140|261|133|\n|drf-granian|2,703|830|198|726|179|\n|ninja-uvicorn|1,533|699|126|584|114|\n|drf-uvicorn|1,035|495|153|447|137|\n\n(fastapi-granian and ninja-granian omitted for brevity - full table in the repo. Zero errors across all 70 measurements.)\n\n**Resource usage:** most configs peak at 195-260MB RAM; drf-granian is the outlier at 456MB (untuned `--blocking-threads`, per the Granian maintainer). CPU: nearly everything saturates \\~85% of the 1-CPU budget under load - except Bolt at 67%.\n\n# Takeaways\n\n* **37x spread on raw JSON collapses to \\~1.9x once PostgreSQL is involved.** For DB-heavy APIs (most of them), query optimization matters far more than framework choice.\n* **Cookie JWT auth costs 5-20% on a DB-heavy endpoint.** Bolt is near-free (it validates the JWT in Rust before Python runs); Litestar pays the most because its auth middleware opens a second DB session to load the user.\n* **uvicorn vs granian isn't one-way**: uvicorn wins CPU-bound JSON for ASGI frameworks, granian wins the DB-bound endpoints, and granian is clearly better for WSGI DRF.\n* **Django Bolt is the one to watch**: top spot on 4 of 7 endpoints at **67% average CPU while everyone else sits \\~85%**, and you keep the Django ORM/admin/ecosystem. Young, and its throughput varies between container starts under a hard CPU cap, but great for side projects already.\n* All caveats (including feedback I haven't addressed yet, like Granian's `--blocking-threads`) are documented in the repo's Methodology secti"}
{"instruction": "When do you prefer asyncio.Semaphore over an asyncio.Queue for limiting concurrency?", "input": "", "output": "When do you prefer asyncio.Semaphore over an asyncio.Queue for limiting concurrency?\nI've been thinking about concurrency control in `asyncio`.\n\nA common pattern for limiting concurrent work is:\n\n    sem = asyncio.Semaphore(10)\n\n    async with sem:\n        await do_work()\n\n\nBut in many cases, couldn't the same problem be modeled by putting work into an `asyncio.Queue` and running a fixed number of worker tasks?\n\nI'm curious how experienced Python developers decide between the two approaches.\n\nAre there real-world situations where a semaphore is clearly the better abstraction than a worker queue? Are there meaningful differences in cancellation behavior, backpressure, fairness, task lifetime, or code complexity?\n\nI'd especially be interested in examples from production async Python code."}
{"instruction": "awesome-python-rs: Curated list of Python libraries and tools powered by Rust", "input": "", "output": "awesome-python-rs: Curated list of Python libraries and tools powered by Rust\nHey [r/Python](https://www.reddit.com/r/Python/)!\n\nMany modern high-performance Python tools now rely on Rust under the hood. Projects like Polars, Ruff, Pydantic v2, orjson, and Hugging Face Tokenizers expose clean Python APIs while using Rust for their performance-critical parts.\n\nI built **awesome-python-rs** to track and discover these projects in one place — a curated list of Python tools, libraries, and frameworks with meaningful Rust components.\n\n# What My Project Does\n\nMaintains a curated list of:\n\n* Python libraries and frameworks powered by Rust\n* Developer tools using Rust for speed and safety\n* Data, ML, web, and infra tools with Rust execution engines\n\nOnly projects with a **meaningful Rust component** are included (not thin wrappers around C libraries).\n\n# Target Audience\n\nPython developers who:\n\n* Care about performance and reliability\n* Are curious how modern Python tools achieve their speed\n* Want examples of successful Python + Rust integrations\n* Are exploring PyO3, maturin, or writing Rust extensions\n\n# Comparison\n\nUnlike general “awesome” lists for Python or Rust, this list is specifically focused on the intersection of the two: Python-facing projects where Rust is a core implementation language. The goal is to make this trend visible and easy to explore in one place.\n\n# Link\n\n* **Repo**: [https://github.com/ritwiktiwari/awesome-python-rs](https://github.com/ritwiktiwari/awesome-python-rs)\n\n# Contribute\n\nIf you know a Python project that uses Rust in a meaningful way, PRs and suggestions are very welcome."}
{"instruction": "City2Graph: A Python library for Graph Neural Networks (GNNs) on geospatial data", "input": "", "output": "City2Graph: A Python library for Graph Neural Networks (GNNs) on geospatial data\n# What My Project Does\n\n[**City2Graph**](https://github.com/c2g-dev/city2graph) is a Python library that converts geospatial datasets into graphs (networks) with an integrated interface for **GeoPandas** (spatial analysis), **NetworkX** (network analysis), and **PyTorch Geometric** (Graph Neural Networks). It lets you build graphs from multiple urban domains:\n\n* **Morphology**: buildings, streets, and land use (from OSM, Overture Maps, etc.)\n* **Transportation**: public transport networks from GTFS (buses, trams, trains)\n* **Mobility**: OD matrices, bike-sharing flows, migration, pedestrian movement\n* **Proximity**: Point data, polygonal boundaries\n\nA key feature is native support for heterogeneous graphs, so you can model complex multi-relational urban systems (e.g. buildings connected to streets connected to bus stops) and convert them directly into PyTorch Geometric HeteroData for GNN workflows.\n\n**Repo:** [**https://github.com/c2g-dev/city2graph**](https://github.com/c2g-dev/city2graph)\n**Doc:** [**https://city2graph.net**](https://city2graph.net)\n\n# Target Audience\n\nAI engineers and data scientists working in GeoAI, urban analytics, spatial data science, or anyone who needs to go from geodata to graph-based machine learning. If you've ever spent hours wrangling shapefiles into a format PyTorch Geometric can consume, this is for you.\n\nIt's also useful for spatial network analysis without the ML side. You can stay in the GeoPandas/NetworkX ecosystem and use it for things like multi-modal accessibility analysis.\n\n# Comparison\n\nThe most popular toolkit for spatial network analysis is [OSMnx](https://osmnx.readthedocs.io/en/stable/), which can retrieve and process the data from OpenStreetMap (OSM).\n\nCity2Graph provides full compatibility to OSMnx, so that users can extend the use of OSM to GNNs or combine it with other layers (e.g., GTFS). Here is how they compare:\n\n|Feature|OSMnx|City2Graph|\n|:-|:-|:-|\n|Primary Use Case|Extraction, simplification, and topological analysis of street networks|Geometric and multi-layered graph construction for GNN integration|\n|Data Sources|OSM|OSM (via OSMnx), Overture Maps, GTFS, OD matrix, and custom geometries.|\n|Graph Representation|Homogeneous graphs (node: intersection / edges: street segments)|Heterogeneous graphs (nodes: intersection, bus station, pointwise location, etc. / edges: street segments, bus lines, distance-based proximity, etc.)|\n|Supported Objects|GeoPandas, NetworkX|GeoPandas, NetworkX, Pytorch Geometric|\n\n# Quickstart\n\nInstall:\n\n    pip install city2graph            # core (GeoPandas + NetworkX)\n    pip install \"city2graph[cpu]\"     # + PyTorch Geometric (CPU)\n    pip install \"city2graph[cu130]\"   # + PyTorch Geometric (CUDA 13.0)\n\n    conda install -c conda-forge city2graph\n    conda install -c conda-forge pytorch pytorch_geometric #cpu\n\nBuild a graph from buildings and streets, then convert to PyG:\n\n    import city2graph as c2g\n\n    # Build morphological graph from buildings and streets\n    nodes, edges = c2g.morphological_graph(buildings_gdf, segments_gdf)\n\n    # Convert to PyTorch Geometric HeteroData\n    hetero_data = c2g.gdf_to_pyg(nodes, edges)\n\n\nBuild a public transport graph from GTFS, then convert to NetworkX:\n\n    gtfs_data = c2g.load_gtfs(\"./gtfs_feed.zip\")\n\n    nodes, edges = c2g.travel_summary_graph(\n        gtfs_data, calendar_start=\"20250601\", calendar_end=\"20250601\""}
{"instruction": "Benchmarks: Kreuzberg, Apache Tika, Docling, Unstructured.io, PDFPlumber, MinerU and MuPDF4LLM", "input": "", "output": "Benchmarks: Kreuzberg, Apache Tika, Docling, Unstructured.io, PDFPlumber, MinerU and MuPDF4LLM\nHi all,\n\nWe finished a bunch of benchmarks of Kreuzberg and other major open source tools in the text-extraction / document-intelligence space. This was very important for us because we practice TDD -> Truth Driven Development, and establishing the baseline is essential.\n\n## Methodology\n\nKreuzberg includes a benchmark harness built in Rust (you can see it in the repo under the `/tools` folder), and the benchmarks run in GitHub Actions CI on Linux runners (see `.github/workflows/benchmarks.yaml`). The goal is to compare extractors on the same inputs with the same measurement approach.\n\n### How we keep comparisons fair:\n- Same fixture set for every tool, and tools only run on file types they claim to support (no forced unsupported conversions).\n- Same iteration count and timeouts per document.\n- Two modes: single-file (one document at a time) to compare latency, and batch (limited concurrency) to compare throughput-oriented behavior.\n\n### What we report:\n- p50/p95/p99 across documents for duration, extraction duration (when available), throughput, memory, and success rate.\n- Optional quality scoring compares extracted text to ground truth.\n\n### CI consolidation:\n- Some tools are sharded across multiple CI jobs; results are consolidated into one aggregated report for this run.\n\n## Benchmark Results\n\nData: 15,288 extractions across 56 file types; 3 measured iterations per doc (plus warmup).\n\nHow these are computed: for each tool+mode, we compute percentiles per file type and then take a simple average across the file types the tool actually ran. These are suite averages, not a single-format benchmark.\n\n### Single-file: Latency\n| Tool | Picked | Types | Success | Duration p50/p95/p99 (ms) | Extraction p50/p95/p99 (ms) |\n|---|---|---:|---:|---:|---:|\n| kreuzberg | `kreuzberg-rust:single` | 56/56 | 99.13% (567/572) | 1.11/7.35/24.73 | 1.11/7.35/24.73 |\n| tika | `tika:single` | 45/56 | 96.19% (530/551) | 9.31/39.76/63.22 | 10.14/46.21/74.42 |\n| pandoc | `pandoc:single` | 17/56 | 92.34% (229/248) | 40.07/88.22/99.03 | 38.68/96.22/109.43 |\n| pymupdf4llm | `pymupdf4llm:single` | 9/56 | 74.02% (94/127) | 79.89/1240.17/7586.50 | 705.37/11146.92/68258.02 |\n| markitdown | `markitdown:single` | 13/56 | 96.26% (309/321) | 128.42/420.52/1385.22 | 114.43/404.08/1365.25 |\n| pdfplumber | `pdfplumber:single` | 1/56 | 96.84% (92/95) | 145.95/3643.88/44101.65 | 138.87/3620.72/43984.61 |\n| unstructured | `unstructured:single` | 25/56 | 94.88% (389/410) | 3391.13/9441.15/11588.30 | 3496.32/9792.28/12028.43 |\n| docling | `docling:single` | 13/56 | 96.07% (293/305) | 14323.02/21083.52/25565.68 | 14277.51/21035.61/25515.57 |\n| mineru | `mineru:single` | 3/56 | 76.47% (78/102) | 33608.01/57333.52/63427.67 | 33603.57/57329.21/63423.63 |\n\n### Single-file: Throughput\n| Tool | Picked | Throughput p50/p95/p99 (MB/s) |\n|---|---|---:|\n| kreuzberg | `kreuzberg-rust:single` | 127.36/225.99/246.72 |\n| tika | `tika:single` | 2.55/13.69/17.03 |\n| pandoc | `pandoc:single` | 0.16/19.45/22.26 |\n| pymupdf4llm | `pymupdf4llm:single` | 0.01/0.11/0.21 |\n| markitdown | `markitdown:single` | 0.17/25.18/31.25 |\n| pdfplumber | `pdfplumber:single` | 0.67/10.74/16.95 |\n| unstructured | `unstructured:single` | 0.02/0.66/0.79 |\n| docling | `docling:single` | 0.10/0.72/0.92 |\n| mineru | `mineru:single` | 0.00/0.01/0.02 |\n\n### Single-file: Memory\n| Tool | Picked | Memory p50/p95/p99 (MB) |\n|---|---|"}
{"instruction": "How on earth do you actually pronounce openpyxl?", "input": "", "output": "How on earth do you actually pronounce openpyxl?\n​I’ve been using this library for a while now, but every time I say it out loud, I second-guess myself.\n\n​Is it \"open-pixel\" or \"open-pie-xl\"?\n\n​\"Open-pixel\" sounds smoother, but since it’s a Python library for Excel, \"open-pie-xl\" (Py as in Python, XL as in Excel) seems more logical.\n\n​How do you guys pronounce it in meetings without sounding like a total amateur?"}
{"instruction": "Building a Python Library in 2026", "input": "", "output": "Building a Python Library in 2026\n[https://stephenlf.dev/blog/python-library-in-2026/](https://stephenlf.dev/blog/python-library-in-2026/)\n\n\nIt seems to me that Astral’s \\`uv\\` is the backbone of any modern Python package. Do you agree? Are we setting ourselves up for disaster by building in Astral’s tooling? How does their acquisition by OpenAI affect things?"}
{"instruction": "Is dotenv the best way to handle credentials on a win server in 2026?", "input": "", "output": "Is dotenv the best way to handle credentials on a win server in 2026?\nHi,\n\ni am working with python on a windows server installation and i dont want to store passwords and api keys direct in my code. Is python-dotenv still the best way to do it today?\n\nthank you very much"}
{"instruction": "Framework speed won't impact your life (or your users), it is probably something else", "input": "", "output": "Framework speed won't impact your life (or your users), it is probably something else\nPeople love debating which web framework is the fastest. We love to brag about using the \"blazing fast\" one with the best synthetic benchmarks. I recently benchmarked a 2x speed difference between two frameworks on localhost, but then I measured a real app deployed to [Fly.io](http://Fly.io) (Ankara to Amsterdam).\n\n**Where the time actually goes:**\n\n* **Framework (FastAPI):** 0.5ms (< 1%)\n* **Network Latency:** 57.0ms\n* **A single N+1 query bug:** 516.0ms\n\n**The takeaway for me was:** Stop picking frameworks based on synthetic benchmarks. Pick for the DX, the docs, and the library support. The \"fast\" framework is the one that lets you ship and find bugs the quickest.\n\nIf you switch frameworks to save 0.2ms but your user is 1,000 miles away or your ORM is doing 300 queries, you’re optimizing for the wrong thing.\n\nFull breakdown and data:\n[https://cemrehancavdar.com/2026/02/19/your-framework-may-not-matter/](https://cemrehancavdar.com/2026/02/19/your-framework-may-not-matter/)"}
{"instruction": "Learn concurrency - a deep dive into multithreading with Python", "input": "", "output": "Learn concurrency - a deep dive into multithreading with Python\nThe article explains concurrency in Python including topics like multithreading, multiprocessing, race conditions, and synchronization mechanisms such as locks. It then takes a deep dive into switching off GIL to enable \\*real\\* multithreading in Python, highlighting the differences, the benefits and the gotchas with clear code examples.\n\nhttps://blog.geekuni.com/2026/04/python-concurrency.html?m=1"}
{"instruction": "Are we happy with SQLAlchemy?", "input": "", "output": "Are we happy with SQLAlchemy?\nI really need the community's opinion on this. I've worked with a lot of ORMs, from Entity Framework to DrizzleORM. SQLAlchemy is the best option we have in the Python ecosystem, but it still sucks compared to ORMs in other ecosystems.\n\nWhen I was working with Go, I discovered sqlc and loved it. It's great, but not enough to replace a full ORM because of its limitations (no dynamic queries).\n\nFor the last five months, I've been building my own equivalent for Python, powered by sqlglot. Unlike sqlc, it has dynamic filters, sorting, and partial updates. It also has a single parameter syntax for all supported dialects (:param), which are Postgres, MySQL, SQLite, DuckDB, and ClickHouse. I borrowed sqlc's end-to-end test cases, and my version passes all of them now.\n\nIt has already replaced SQLAlchemy for me in several microservices. So I guess my question is: is it worth continuing to build it? Because I don’t really know if other Python devs need such tool.\n\nI've had a lot of fun building the current version, and I have a long roadmap ahead. That includes migrations (with auto-generation when possible), generators for other languages, and much more."}
{"instruction": "GoPdfSuit v4.2.0: High-Performance PDF Engine & Package for Python (Native Go Speed, No Layout Code)", "input": "", "output": "GoPdfSuit v4.2.0: High-Performance PDF Engine & Package for Python (Native Go Speed, No Layout Code)\nI’m Chinmay, the author of **GoPdfSuit**, and I’m excited to share that we just hit **390+ stars** and launched **v4.2.0**!\n\nFirstly, let me thank you all for the response on the [last post](https://www.reddit.com/r/Python/comments/1qno6hj/gopdfsuit_v400_a_highperformance_pdf_engine_for/). After chatting with some of you, I realized that while the community loved the speed, some were hesitant about running an extra microservice. In this update, we’ve addressed that head-on with official Python bindings.\n\n# What My Project Does\n\nGoPdfSuit is a high-performance PDF generation engine that decouples design from code. Instead of writing layout logic (x, y coordinates) inside your Python scripts, you use a **Visual Drag-and-Drop Editor** to design your PDF. The editor exports a JSON template, and the GoPdfSuit engine (now available as a Python package) merges your data into that template to generate PDFs at native Go speeds.\n\n**Key Features in v4.2.0:**\n\n* **Official Python Bindings:** You can now leverage the power of Go directly within your Pythonic workflows—no sidecar container required.\n* **Vector SVG Support:** Native support for embedding SVG images, perfect for high-quality branding and charts.\n* **Sophisticated Text Wrapping:** The engine handles complex wrapping logic automatically to ensure content fits your defined boundaries.\n* **Visual Editor Enhancements:** A React-based drag-and-drop editor for live previews.\n\n# Target Audience\n\nIt is suitable for both small-scale scripts and high-volume production environments.\n\nWe now offer two approaches based on your needs:\n\n1. **The Library Approach (New):** For developers who want to `pip install` a package and keep everything in their Python environment. The heavy lifting is done by the Go core via bindings.\n2. **The Service Approach:** For high-volume production apps (1,000+ PDFs/min). You can deploy the engine as a standalone container on GCP Cloud Run or AWS Lambda to prevent PDF generation from blocking your main Python app's event loop.\n\n# Comparison\n\nIf you've used **ReportLab** or **JasperReports**, you likely know the pain of manually coding `x, y` coordinates for every line and logo.\n\n* **vs. ReportLab:** ReportLab often requires extensive boilerplate code to define layouts, making maintenance a nightmare when designs change. GoPdfSuit solves this by using a **Visual Editor** and JSON templates. If the layout needs to change, you update the JSON—**zero Python code changes required.**\n* **vs. Pure Python Libraries:** GoPdfSuit's core engine is built in Go, offering performance that pure Python libraries typically can't touch.\n   * *Average generation time:* \\~13.7ms\n   * *PDF Size:* \\~130 KB (highly optimized)\n* **Compliance:** Unlike many lightweight tools, we have built-in support for **PDF/UA-2 (Accessibility)** and **PDF/A (Archival)**.\n\n# Links & Resources\n\n* **GitHub Repository:** [github.com/chinmay-sawant/gopdfsuit](https://github.com/chinmay-sawant/gopdfsuit)\n* **Website & Editor:** [chinmay-sawant.github.io/gopdfsuit](https://chinmay-sawant.github.io/gopdfsuit/)\n* **Documentation:** Check out the new \"How-to\" guides and Python client examples in the repo. [Documentation Link](https://chinmay-sawant.github.io/gopdfsuit/#/documentation)\n\nAs this is a free open-source project, your **Stars ⭐** are the fuel that keeps us motivated."}
{"instruction": "After 2 years of development, I'm finally releasing Eventum 2.0", "input": "", "output": "After 2 years of development, I'm finally releasing Eventum 2.0\n# What My Project Does\n\n**Eventum** generates realistic synthetic events - logs, metrics, clickstream, IoT, etc., and streams them in real time or dumps everything at once to various outputs.\n\nIt started because I was working with SIEM systems and constantly needed test data. Every time: write a script, hardcode values, throw it away. Got tired of that loop.\n\nThe idea of Eventum is pretty simple - write an event template, define a schedule and pick where to send it.\n\n**Features:**\n\n* **Faker, Mimesis, and any Python package** directly in templates\n* **Finite state machines** \\- model stateful sequences (e.g.login > browse > checkout)\n* **Statistical traffic patterns** \\- mimic real-world traffic curves defined in config\n* **Three-level shared state** \\- templates can share data within or across generators\n* **Fan-out with formatters** \\- deliver to files, ClickHouse, OpenSearch, HTTP simultaneously\n* **Web UI, REST API, Docker, encrypted secrets** \\- and other features\n\n**Tech stack:** Python 3.13, asyncio + uvloop, Pydantic v2, FastAPI, Click, Jinja2, structlog. React for the web UI.\n\n# Target Audience\n\nTesters, data engineers, backend developers, DevOps, SRE and data specialists, security engineers and anyone building or testing event-driven systems.\n\n# Comparison\n\nI honestly haven’t found anything with this level of flexibility around time control and event correlation. Most generators either spit out random-ish data or let you tweak a few fields - but you can’t really model realistic temporal behavior, chained events or causal relationships in a simple way.\n\nWould love to hear what you think!\n\n**Links:**\n\n* Docs: [eventum.run](https://eventum.run/)\n* GitHub: [github.com/eventum-generator/eventum](https://github.com/eventum-generator/eventum)"}
{"instruction": "Do you actually read the source code of libraries you install?", "input": "", "output": "Do you actually read the source code of libraries you install?\nHonest question.\nWith all the supply chain attacks recently i've been wondering how many people actually look at what they're pip installing. I check the repo, scan the star count, maybe skim the readme. but reading actual source? almost never unless its a small package.\n\nHow do you decide what to trust?"}
{"instruction": "369 problems for \"109 Python Problems\" completed", "input": "", "output": "369 problems for \"109 Python Problems\" completed\nI completed today the third and the final part of the problem collection 109 Python Problems for CCPS 109, bringing the total number of problems to 3 * 123 = 369. With that update, the collection is now in its final form in that its problems are set in stone, and I will move on to create something else in my life.\nCurated over the past decade and constantly field tested in various courses in TMU, this problem collection contains coding problems suitable for beginning Python learners all the way to the senior level undergraduate algorithms and other computer science courses. I wanted to include unusual problems that you don't see in textbooks and other online problem collections so that these problems involve both new and classic concepts of computer science and discrete math. Students will decide if I was successful in this.\nThese problems were inspired by all the recreational math materials on books and YouTube channels that I have watched over the past ten years. I learned a ton of new stuff myself just by understanding this material to be able to implement it efficiently and effectively.\nThe repository is fully self-contained, and comes with fully automated fuzz tester script to instantly check the correctness of student solutions. I hope that even in this age of vibe coding and the emergence of superhuman LLM's that can solve all these problems on a spot, this problem collection will continue to be useful for anyone over the world who wants to get strong at coding, Python and computer science."}
{"instruction": "Oxyde: async type-safe Pydantic-centric Python ORM", "input": "", "output": "Oxyde: async type-safe Pydantic-centric Python ORM\nHey everyone!\n\nSharing a project I've been working on: **Oxyde ORM**. It's an async ORM for Python with a Rust core that uses Pydantic v2 for models.\n\n---\n\n**GitHub:** [github.com/mr-fatalyst/oxyde](https://github.com/mr-fatalyst/oxyde)\n\n**Docs:** [oxyde.fatalyst.dev](https://oxyde.fatalyst.dev/)\n\n**PyPI:** `pip install oxyde`\n\n**Benchmarks repo:** [github.com/mr-fatalyst/oxyde-benchmarks](https://github.com/mr-fatalyst/oxyde-benchmarks)\n\n**FastAPI example:** [github.com/mr-fatalyst/fastapi-oxyde-example](https://github.com/mr-fatalyst/fastapi-oxyde-example)\n\n---\n\n## Why another ORM?\n\nThe main idea is a **Pydantic-centric ORM**.\n\nExisting ORMs either have their own model system (Django, SQLAlchemy, Tortoise) or use Pydantic as a wrapper on top (SQLModel). I wanted an ORM where Pydantic v2 models are first-class citizens, not an adapter.\n\n**What this gives you:**\n- Models are regular Pydantic BaseModel with validation, serialization, type hints\n- No magic with descriptors and lazy loading\n- Direct FastAPI integration (models can be returned from endpoints directly)\n- Data validation happens in Python (Pydantic), query execution happens in Rust\n\nThe API is Django-style because `Model.objects.filter()` is a proven UX.\n\n---\n\n## What My Project Does\n\nOxyde is an async ORM for Python with a Rust core that uses Pydantic v2 models as first-class citizens. It provides Django-style query API (`Model.objects.filter()`), supports PostgreSQL/MySQL/SQLite, and offers significant performance improvements through Rust-powered SQL generation and connection pooling via PyO3.\n\n## Target Audience\n\nThis is a production-ready library for Python developers who:\n- Use FastAPI or other async frameworks\n- Want Pydantic models without ORM wrappers\n- Need high-performance database operations\n- Prefer Django-style query syntax\n\n## Comparison\n\nUnlike existing ORMs:\n- **Django/SQLAlchemy/Tortoise**: Have their own model systems; Oxyde uses native Pydantic v2\n- **SQLModel**: Uses Pydantic as a wrapper; Oxyde treats Pydantic as the primary model layer\n- **No magic**: No lazy loading or descriptors — explicit `.join()` for relations\n\n---\n\n## Architecture\n\n```\n┌─────────────────────────────────────┐\n│      Python Layer                │\n│  OxydeModel (Pydantic v2)        │\n│  Query DSL (Django-like)         │\n│  AsyncDatabase                   │\n└───────────────┬─────────────────────┘\n               │ MessagePack\n               ▼\n┌─────────────────────────────────────┐\n│      Rust Core (PyO3)            │\n│  IR parsing                      │\n│  SQL generation (sea-query)      │\n│  Connection pools (sqlx)         │\n└───────────────┬─────────────────────┘\n               ▼\n   PostgreSQL / SQLite / MySQL\n```\n\n### How it works\n\n1. Python builds a query via DSL, producing a dict (Intermediate Representation)\n2. Dict is serialized to MessagePack and passed to Rust\n3. Rust deserializes IR, generates SQL via sea-query\n4. sqlx executes the query, result comes back via MessagePack\n5. Pydantic validates and creates model instances\n\n---\n\n## Code example\n\n```python\nfrom oxyde import OxydeModel, Field, db\n\nclass User(OxydeModel):\n    id: int | None = Field(default=None, db_pk=True)\n    name: str\n    email: str = Field(db_unique=True)\n    age: int | None = None\n\n    class Meta:\n        is_table = True\n\nasync def main():\n    await db.init(default=\"postgresql://localhost/mydb\")\n\n    # Create\n    user = await User.objects.create(name=\"Alice"}
{"instruction": "Do you guys write code on paper or only in IDE?", "input": "", "output": "Do you guys write code on paper or only in IDE?\nI recently tried solving small Python problems on paper and it felt harder but also made me think more.\n\nDo you think this helps in making concepts more Runable in your head, or is it just unnecessary struggle?"}
{"instruction": "Why is there no standard for typing array dimensions?", "input": "", "output": "Why is there no standard for typing array dimensions?\nWhy is there no standard for typing array dimensions?\nIn data science, it really usefull to indicate wether something is a vector or a matrix (or a tensor with more dimensions). One up in complexity, its usefull to indicate wether a function returns something with the same size or not.\n\nUnless I am missing something, a standard for this is lacking. Of course I understand that typing is not enforced in python, and i am not aksing for this, i just want to make more readable functions. I think numpy and scipy 'solve' this by using the docstring. But would it make sense to specifiy array dimensions & sizes in the function signature?"}
{"instruction": "Pandas 3.0 vs pandas 1.0 what's the difference?", "input": "", "output": "Pandas 3.0 vs pandas 1.0 what's the difference?\nhey guys, I never really migrated from 1 to 2 either as all the code didn't work. now open to writing new stuff in pandas 3.0. What's the practical difference over pandas 1 in pandas 3.0? Is the performance boosts anything major? I work with large dfs often 20m+ and have lot of ram. 256gb+.\n\nAlso, on another note I have never used polars. Is it good and just better than pandas even with pandas 3.0. and can handle most of what pandas does? So maybe instead of going from pandas 1 to pandas 3 I can just jump straight to polars?\n\nI read somewhere it has worse gis support. I do work with geopandas often. Not sure if it's gonna be a problem. Let me know what you guys think. thanks."}
{"instruction": "Scaling NumPy on Free-Threaded Python", "input": "", "output": "Scaling NumPy on Free-Threaded Python\n> NumPy is the foundational array library in the scientific Python ecosystem. Every numerical, machine learning, and data analysis library in Python either depends on NumPy directly or interoperates with it. As the free-threaded build of CPython matures, NumPy is one of the first libraries that users reach for when trying to scale CPU-bound numerical workloads across multiple cores using threads.\n>\n>In this blog post, I will walk through the work I did over the last few months in both NumPy and CPython to eliminate the multi-threaded scaling bottlenecks that were preventing NumPy from scaling on free-threaded Python.\n\nhttps://labs.quansight.org/blog/scaling-numpy-on-free-threaded-python"}
{"instruction": "Python 3.15.0 RC1 Is Here — Python 3.15 Is Almost Ready 🚀", "input": "", "output": "Python 3.15.0 RC1 Is Here — Python 3.15 Is Almost Ready 🚀\n&#x200B;\n\nThis is an important milestone because the Python team has now entered the release-candidate phase. At this stage, only reviewed changes that are considered clear bug fixes are expected to be accepted before the final release.\n\nWhy this matters\n\nPython 3.15 has been going through several alpha and beta releases during 2026, and RC1 means the development cycle is getting very close to the final version.\n\nThe Python team currently plans two release candidates before the final Python 3.15.0 release.\n\nI'm curious about one thing:\n\nAre you planning to move your projects to Python 3.15 when the stable release arrives, or will you wait a few months before upgrading?\n\nWhat new Python 3.15 feature are you most interested in?\n\nSource: Python Insider / Python.org"}
{"instruction": "packaging 26.0rc1 is out for testing and is multiple times faster", "input": "", "output": "packaging 26.0rc1 is out for testing and is multiple times faster\nPyPI: https://pypi.org/project/packaging/26.0rc1/\n\nRelease Notes: https://github.com/pypa/packaging/blob/main/CHANGELOG.rst#260rc1---[PHONE]\n\nBlog by another maintainers on the performance improvements: https://iscinumpy.dev/post/packaging-faster/\n\n`packaging` is one the foundational libraries for Python packaging tools, and is used by pip, Poetry, pdm etc. I recently became a maintainer of the library to help with things I wanted to fix for my work on pip (where I am also a maintainer).\n\nIn some senses it's fairly niche, in other senses it's one of the most widely used libraries in Python, we made a lot of changes in this release, a significant amount to do with performance, but also a few fixes in buggy or ill defined behavior in edge case situations. So I wanted to call attention to this release candidate, which is fairly unusual for packaging.\n\nLet me know if you have any questions, I will do my best to answer."}
{"instruction": "Who's going to PyCon US next week?", "input": "", "output": "Who's going to PyCon US next week?\nMe\\* ✋ I hope to see a good number of you all in Long Beach, too!\n\nIf you're curious what PyCon US is about, you can take a look at the [schedule](https://us.pycon.org/2026/schedule/), the [list of events](https://us.pycon.org/2026/events/), and the list of companies that will be in [the Expo Hall](https://us.pycon.org/2026/attend/expo-hall/). But really the formal program is only like half of the experience. It's a gathering of 2K+ people who are all there for the love of Python, and just want to spend a weekend+ talking about it and learning about it and also just hanging out shooting the ~~sh~~breeze or playing board games or whatever with a like-minded group of people. The best description of it I've heard is \"like a family reunion you actually want to go to.\"\n\nFWIW I'm v happy to answer questions if you've got 'em; it is the time of year when I am living and breathing PyCon US so the odds are very good I know the answer to whatever it is you are wondering about:)\n\n\\*well, I have to because it is my job 😅 I work for the Python Software Foundation, the non-profit behind Python and also PyCon US. But there are many other good reasons to go:)"}
{"instruction": "What backend projects would actually aid me stand out for a junior Python backend developer role?", "input": "", "output": "What backend projects would actually aid me stand out for a junior Python backend developer role?\nHi everyone,\nI’m currently preparing for junior Python backend developer roles, mainly focusing on FastAPI, PostgreSQL, SQLAlchemy, Docker, Git, and REST APIs.\nWhen I search online, I always see the same project recommendations:\nTodo API\nBlog API\nLibrary Management System\nExpense Tracker\nURL Shortener\nE-commerce API\nMy concern is that almost every beginner seems to build these projects. If recruiters have seen hundreds of them, do they still add value to a portfolio, or do they just blend in?\nWould it be better to build something that’s closer to a real business application, such as:\nRecruitment/HR management\nClinic management\nWarehouse/inventory system\nInternal business tools\nAPI gateway or authentication service\nI’m trying to optimize my time and build projects that will genuinely improve my chances of landing a junior backend role rather than just checking boxes.\nFor those of you who interview junior developers or work as backend engineers:\nWhat projects actually impress you?\nIs the project idea important, or is the quality of the implementation what matters most?\nWhat features make you think, “This candidate knows backend development”?\nI’d really appreciate hearing from people who have interviewed candidates or recently landed backend jobs themselves.\nThanks!"}
{"instruction": "Understanding Python’s typing system (draft guide, 3.14)", "input": "", "output": "Understanding Python’s typing system (draft guide, 3.14)\nHi all — I’ve been working on a Python 3.14 typing guide and am sharing it publicly in hopes that other people find it useful and/or can make it better.\n\nIt’s not a reference manual or a PEP summary. It’s an attempt to explain how Python’s typing system behaves *as a system* — how inference, narrowing, boundaries, and async typing interact, and how typing can be used as a way of reasoning about code rather than just silencing linters.\n\nIt’s long, but modular; you can drop into any section. The main chunks are:\n\n* What Python typing is (and is not) good at\n* How checkers resolve ambiguity and refine types\n* Typing data at boundaries (TypedDict vs parsing)\n* Structural typing, guards, match, and resolution\n* Async typing and control flow\n* Architectural patterns and tradeoffs\n\nIf you’ve ever felt that typing “mostly works but feels opaque,” this is aimed at that gap.\n\nIf you notice errors, confusing explanations, or places where it breaks down in real usage, I’d appreciate hearing about it — even partial or section-level feedback helps.\n\nRepo: [https://github.com/JBogEsq/python_type_hinting_guide](https://github.com/JBogEsq/python_type_hinting_guide)"}
{"instruction": "Building a Python Framework in Rust Step by Step to Learn Async", "input": "", "output": "Building a Python Framework in Rust Step by Step to Learn Async\nI wanted ~~an excuse to smuggle rust into more python projects~~ to learn more about building low level libs for Python, in particular async. See while I enjoy Rust, I realize that not everyone likes spending their Saturdays suffering ownership rules, so the combination of a low level core lib exposed through high level bindings seemed really compelling (why has no one [thought](https://github.com/pola-rs/polars) of [this](https://github.com/huggingface/tokenizers) [before](https://pydantic.dev/articles/pydantic-v2#motivation--pydantic-core)?). Also, as a possible approach for building team tooling / team shared libs.\n\nAnyway, I have a repo, video guide and companion blog post walking through building a python web framework (similar ish to flask / fast API) in rust step by step to explore that process / setup. I should mention the goal of this **was to learn and explore using Rust and Python together and not to build / ship a framework for production use**. Also, there already is a fleshed out Rust Python framework called [Robyn](https://github.com/sparckles/Robyn), which is supported / tested, etc.\n\n* repo: [https://github.com/matthewhaynesonline/Pyper](https://github.com/matthewhaynesonline/Pyper)\n* blog: [https://blog.studiohaynes.com/2026/02/22/two-loops-one-app.html](https://blog.studiohaynes.com/2026/02/22/two-loops-one-app.html)\n* video guide: [https://youtu.be/u8VYgITTsnw](https://youtu.be/u8VYgITTsnw)\n\nIt's not a silver bullet (especially when I/O bound), but there are some definite perf / memory efficiency benefits that could make the codebase / toolchain complexity worth it (especially on that efficiency angle). The pyo3 ecosystem (including maturin) is really frickin awesome and it makes writing rust libs for Python an appealing / tenable proposition IMO. Though, for async, wrangling the dual event loops (even with pyo3's async runtimes) is still a bit of a chore."}
{"instruction": "What Python Tools Do You Use for Data Visualization and Why?", "input": "", "output": "What Python Tools Do You Use for Data Visualization and Why?\nData visualization is crucial for interpreting complex datasets, and Python offers a variety of tools to accomplish this. I'm curious to know which libraries or frameworks you prefer for data visualization and what features make them stand out for you. For instance, do you lean towards Matplotlib for its flexibility, Seaborn for its ease of use, or perhaps Plotly for interactive plots? Additionally, how do you handle specific challenges, such as customizing visualizations or integrating them into web applications? Sharing your experiences and use cases could be beneficial for those looking to enhance their data storytelling skills. Let's discuss the strengths and weaknesses of different tools and any tips you may have for getting the most out of them."}
{"instruction": "Onlymaps v0.2.0 has been released!", "input": "", "output": "Onlymaps v0.2.0 has been released!\nOnlymaps is a Python micro-ORM library intended for those those who'd rather use plain SQL to talk to a database instead of having to set up some full-fledged ORM, but at the same time don't want to deal with low-level concepts such as cursors, mapping query results to Python objects etc...\n\n[https://github.com/manoss96/onlymaps](https://github.com/manoss96/onlymaps)\n\n# What my project does\n\nOnlymaps makes it extremely easy to connect to almost any SQL-based database and execute queries by providing a dead simple API that supports both sync and async query execution via either a connection or a connection pool. It integrates well with Pydantic so as to enable fine-grained type validation:\n\n    from onlymaps import connect\n    from pydantic import BaseModel\n\n    class User(BaseModel):\n        name: str\n        age: int\n\n    with connect(\"mysql://user:password@localhost:5432/mydb\", pooling=True) as db:\n\n       users: list[User] = db.fetch_many(User, \"SELECT name, age FROM users\")\n\nThe v0.2.0 version includes the following:\n\n1. Support for OracleDB and DuckDB databases.\n2. Support for `decimal.Decimal` type.\n3. Bug fixes.\n\n# Target Audience\n\nOnlymaps is best suited for use in Python scripts that need to connect to a database and fetch/update data. It does not provide advanced ORM features such as database migrations. However, if your toolset allows it, you can use Onlymaps in more complex production-like environments as well, e.g. long-running ASGI servers.\n\n# Comparison\n\nOnlymaps is a simpler more lightweight alternative to full-fledged ORMs such as SQLAlchemy and Django ORM, for those that are only interested in writing plain SQL."}
{"instruction": "I made a decorator based auto-logger!", "input": "", "output": "I made a decorator based auto-logger!\nHi guys!\n\nI've attended Warsaw IT Days 2026 and the lecture \"Logging module adventures\" was really interesting.\nI thought that having filters and such was good long term, but for short algorithms, or for beginners, it's not something that would be convenient for every single file.\n\n# So I made LogEye!\n\nHere is the repo: https://github.com/MattFor/LogEye\nI've also learned how to publish on PyPi: [https://pypi.org/project/logeye/](https://pypi.org/project/logeye/)\nThere are also a lot of tests and demos I've prepared, they're on the git repo\n\nI'd be really really grateful if you guys could check it out and give me some feedback\n\n### What My Project Does\n* Automatically logs variable assignments with inferred names\n* Infers variable names at runtime (even tuple assignments)\n* Tracks nested data structures dicts, lists, sets, objects\n* Logs mutations in real time `append`, `pop`, `setitem`, `add`, etc.\n* Traces function calls, arguments, local variables, and return values\n* Handles recursion and repeated calls `func`, `func_2`, `func_3` etc.\n* Supports inline logging with a pipe operator `\"value\" | l`\n* Wraps callables (including lambdas) for automatic tracing\n* Logs formatted messages using both `str.format` and `$template` syntax\n* Allows custom output formatting\n* Can be enabled/disabled globally very quickly\n* Supports multiple path display modes (absolute / project / file)\n* No setup just import and use\n\n# Target Audience\n\n### LogEye is mainly for:\n\n* beginners learning how code executes\n* people debugging algorithms or small scripts\n* quick prototyping where setting up logging/debuggers are a bit overkill\n\nIt is not intended for production logging systems or performance-critical code, it would slow it down way too much.\n\n# Comparison\n\nCompared to Python's existing logging module:\n\n* logging requires setup (handlers, formatters, config)\n* LogEye works immediately, just import it and you can use it\n\nCompared to using print():\n\n* print() requires manual placement everywhere\n* LogEye automatically tracks values, function calls, and mutations\n\nCompared to debuggers:\n\n* debuggers are interactive but slower to use for quick inspection\n* LogEye gives a continuous execution trace without stopping the program\n\n# Usage\n\nSimply install it with\n\n```bash\npip install logeye\n```\n\nand then import is like this:\n\n```python\nfrom logeye import *\n```\n\nHere's an example:\n\n```python\nfrom logeye import *\n\nx = log(10)\n\n@log\ndef add(a, b):\n    total = a + b\n    return total\n\nadd(2, 3)\n```\n\nOutput:\n\n```commandline\n[0.002s] print.py:3 (set) x = 10\n[0.002s] print.py:10 (call) add = {'args': (2, 3), 'kwargs': {}}\n[0.002s] print.py:7 (set) add.a = 2\n[0.002s] print.py:7 (set) add.b = 3\n[0.002s] print.py:8 (set) add.total = 5\n[0.002s] print.py:8 (return) add = 5\n```\n\nHere's a more advanced example with Dijkstras algorithm\n\n```python\nfrom logeye import *\n\n@log\ndef dijkstra(graph, start):\n\tdistances = {node: float(\"inf\") for node in graph}\n\tdistances[start] = 0\n\n\tvisited = set()\n\tqueue = [(0, start)]\n\n\twhile queue:\n\n\t\tcurrent_dist, node = queue.pop(0)\n\n\t\tif node in visited:\n\t\t\tcontinue\n\n\t\tvisited.add(node)\n\n\t\tfor neighbor, weight in graph[node].items():\n\t\t\tnew_dist = current_dist + weight\n\n\t\t\tif new_dist < distances[neighbor]:\n\t\t\t\tdistances[neighbor] = new_dist\n\t\t\t\tqueue.append((new_dist, neighbor))\n\n\t\tqueue.sort()\n\n\treturn distances\n\ngraph = {\n\t\"A\": {\"B\": 1, \"C\": 4},\n\t\"B\": {\"C\": 2, \"D\": 5},\n\t\"C\": {\"D\": 1},\n\t\"D\": {}"}
{"instruction": "What's your favorite Python library for automating Excel workflows?", "input": "", "output": "What's your favorite Python library for automating Excel workflows?\n&#x200B;\n\nI've seen people use pandas, openpyxl, xlwings, and even custom scripts for filtering, reporting, and chart generation. Curious what works best for real-world projects."}
{"instruction": "I wrote a comprehensive guide to NATS — the messaging system that replaces Kafka, Redis, and RabbitM", "input": "", "output": "I wrote a comprehensive guide to NATS — the messaging system that replaces Kafka, Redis, and RabbitM\nI've been working with Kafka and aiokafka in production and kept running into the same limitations — partition rebalancing, watermark commits, DLQ as an afterthought.\n\nNATS with JetStream solves most of these at the protocol level. This guide covers the full mental model with Python examples using [nats.py](http://nats.py) throughout — pub/sub, JetStream pull consumers, per-message acks, graceful shutdown with asyncio, and the new 2.11/2.12 features.\n\nFull post: [https://open.substack.com/pub/scalebites/p/i-replaced-kafka-redis-and-rabbitmq?r=7hzmj&utm\\_campaign=post&utm\\_medium=web&showWelcomeOnShare=true](https://open.substack.com/pub/scalebites/p/i-replaced-kafka-redis-and-rabbitmq?r=7hzmj&utm_campaign=post&utm_medium=web&showWelcomeOnShare=true)"}
{"instruction": "I built a Python framework for creating native macOS menu bar apps", "input": "", "output": "I built a Python framework for creating native macOS menu bar apps\nHey everyone! In the past years I've used python to do basically anything, there are really few things python can't do. Unfortunately one of them is creating rich, extensively customizable macOS statusbar apps (guis in general, but with projects like Flet we are getting there).                                                                                                                This is why I've been working on Nib, a Python framework that lets you build native macOS menu bar applications with a declarative, SwiftUI-inspired API.\n\nFor anyone curious on how it works you can read about it here: https://bbalduzz.github.io/nib/concepts/, but basically you write python, Nib renders native SwiftUI. Two processes connected over a Unix socket, Python owns the logic, Swift owns the screen. No Electron, no web views, just a real native app (yay!).\n\n### What My Project Does\n\nNib lets you write your entire menu bar app in Python using a declarative API, and it renders real native SwiftUI under the hood. What it brings to the table (or better say desktop):\n- 30+ SwiftUI components (text, buttons, toggles, sliders, charts, maps, canvas, etc.) and counting :)\n- Reactive updates: mutate a property, UI updates automatically\n- System services: battery, notifications, keychain, camera, hotkeys, clipboard\n- Hot reload with nib run\n- Build standalone .app bundles with nib build\n- Settings persistence, file dialogs, drag & drop etc..\n\n### Target Audience\n\nPython devs on macOS who want to build small utilities, status bar tools, or productivity apps without learning Swift. It's usable today but still evolving — I'm using it for my own apps.\n\n### Comparison\n\n- _Rumps_: menu bar apps in Python but limited to basic menus, no rich UI\n- _py2app_: bundles Python as .app but doesn't give you native UI\n- _Flet_: cross-platform Flutter-based GUIs, great but not native macOS and not menu bar focused\n- _SwiftBar/xbar_: run scripts in the menu bar but output is just text, no interactive UI\n\nNib is the only option that gives you actual SwiftUI rendering with a full component library, specifically for menu bar apps.\n\n### Links:\n- GitHub: https://github.com/Bbalduzz/nib\n- Docs: https://bbalduzz.github.io/nib/\n\nWith this being said I would love feedback! Especially on the API design and what components you'd want to see next."}
{"instruction": "Percentage formatting or f-strings with logging?", "input": "", "output": "Percentage formatting or f-strings with logging?\nI'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?"}
{"instruction": "Python format string visualizer", "input": "", "output": "Python format string visualizer\nI'm going through the book [Effective Python](https://effectivepython.com/) by Brett Slatkin and got bogged down by f-string formatting (literally in Chapter 1; cue eyeroll). I thought there might be a tool like Pythex (for f-strings) but I couldn't find anything. Got Claude to whack out a quick HTML app using the spec from help('FORMATTING'). Might be helpful to someone learning.\n\n[Repo](https://github.com/genericpenguin/python-format-string) and [Page](https://genericpenguin.github.io/python-format-string/)"}
{"instruction": "rsloop: An event loop for asyncio written in Rust", "input": "", "output": "rsloop: An event loop for asyncio written in Rust\nactually, nothing special about this implementation. just another event loop written in rust for educational purposes and joy\n\nin tests it shows seamless migration from uvloop for my scraping framework [https://github.com/BitingSnakes/silkworm](https://github.com/BitingSnakes/silkworm)\n\nwith APIs (fastapi) it shows only one advantage: better p99, uvloop is faster about 10-20% in the synthetic run\n\ncurrently, i am forking on the win branch to give it windows support that uvloop lacks\n\ncode: [https://github.com/RustedBytes/rsloop](https://github.com/RustedBytes/rsloop)\n\nfields of this redidit:\n\n\\- what the library does: it implements event loop for asyncio\n\n\\- comparison: i will make it later with numbers\n\n\\- target audience: everyone who uses asyncio in python\n\nPS: the post written using human's fingers, not by AI"}
{"instruction": "Best Python framework for industry-level desktop app? (PySide/PyQt/wxPython/Kivy/Web approacg)", "input": "", "output": "Best Python framework for industry-level desktop app? (PySide/PyQt/wxPython/Kivy/Web approacg)\nHi everyone,\nI have around 5 years of experience in IT and I’m planning to build complex, industry-level desktop applications using Python.\nI’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:\nPySide (Qt for Python)\nPyQt\nwxPython\nKivy\nPython backend + web frontend (React/Angular) wrapped in Electron\nMy goal is strictly desktop applications (not SaaS/web apps), and I’m trying to choose something that is:\nUsed in the industry\nScalable for large applications\nGood for long-term maintainability and career growth\nFrom what I’ve researched:\nQt-based (PySide/PyQt) seems most powerful\nwxPython looks more native but less modern\nKivy seems more for touch/mobile-style apps\nWeb-based approach looks modern but heavier\nI’d really like input from people with real industry experience:\n👉 Which of these is actually used in companies for serious desktop applications?\n👉 Is PySide preferred over PyQt nowadays?\n👉 Is wxPython or Kivy used in production anywhere significant?\n👉 When does it make sense to choose a web-based desktop app instead?\nWould really appreciate honest opinions and real-world insights.\nThanks!"}
{"instruction": "One of the most influential Python video", "input": "", "output": "One of the most influential Python video\nVideo: \"https://www.youtube.com/watch?v=ZW5\\_eEKEC28\"\nTitle: \"Seattle Conference on Scalability: YouTube Scalability\"\n\nSo long story short, when I started my Python career 10 years ago, I came across a 2007 Google talk that completely stunned me, and is probably the reason I chose Python somehow.\n\nThe then-engineering manager Cuong Do, explained basically why they choose Python and the YT backend-general architecture.\n\nHow they scale with it (they were exploding at that time) and how they managed its performance.\n\nHe also explains the fact that, the most impactful cost of a company is not the infrastructure, but the engineers (if I remember correctly, he quantified the cost in about 60% of the total annual cost of YT company in that year).\n\nJust wanna share it since it's a real gem today. You won't find it with a simple search on YT anymore (old, and unfortunately not many views, which makes it even more valuable I think)."}
{"instruction": "Is there ever a point where you don't feel like an idiot?", "input": "", "output": "Is there ever a point where you don't feel like an idiot?\nLike I have fun coding in python and making dumb little projects, but every time i do, I'm always thinking about how there's probably a better way to do it. And know that I'm trying to explore doing things with a raspberry pi, I just feel really dumb. Like everything I do doesn't matter as much because there is probably a better way to do what I did."}
{"instruction": "GoPdfSuit v4.0.0: A high-performance PDF engine for Python devs (No Go knowledge required)", "input": "", "output": "GoPdfSuit v4.0.0: A high-performance PDF engine for Python devs (No Go knowledge required)\nI’m the author of **GoPdfSuit** ([https://github.com/chinmay-sawant/gopdfsuit](https://github.com/chinmay-sawant/gopdfsuit)), and we just hit **350+ stars** and launched **v4.0.0** today! I wanted to share this with the community because it solves a pain point many of us have had with legacy PDF libraries: manual coordinate-based coding.\n\n# What My Project Does\n\nGoPdfSuit is a high-performance PDF generation engine that allows you to design layouts visually and generate documents via a simple Python API.\n\n* **Drag-and-Drop Editor:** Includes a React-based UI to design your PDF. It exports a JSON template, so you never have to manually calculate `x,y` coordinates again.\n* **Python Integration:** You interact with the engine purely via standard Python `requests` (HTTP/JSON). You deploy the container/binary once and just hit the endpoint from your Python scripts.\n* **Compliance:** Supports Arlington Compatibility, PDF/UA-2 (Accessibility), and PDF/A (Archival) out of the box.\n\n# Target Audience\n\nThis is built for **Production Use**. It is specifically designed for:\n\n* **Developers** who need to generate complex reports (invoices, financial statements) but find existing libraries slow or hard to maintain.\n* **Enterprise Teams** requiring strict PDF compliance (accessibility and archival standards).\n* **High-Volume Apps** where PDF generation is a bottleneck (e.g., generating 1,000+ PDFs per minute).\n\n# Comparison (How it differs from ReportLab/JasperReports)\n\n|**Feature**|**ReportLab / JasperReports**|**GoPdfSuit**|\n|:-|:-|:-|\n|**Layout Design**|Manual code / XML|Visual Drag-and-Drop|\n|**Performance**|Python-level speed / Heavy Java|Native Go speed (\\~70ms execution)|\n|**Maintenance**|Changing a layout requires code edits|Change the JSON template; no code changes|\n|**Compliance**|Requires extra plugins/config|Built-in PDF/UA and PDF/A support|\n\n# Performance Benchmarks\n\nTested on a standard financial report template including XMP data, image processing, and bookmarks:\n\n* **Go Engine Internal Logic:** \\~61.53ms\n* **Total Python Execution (Network + API):** \\~73.08ms\n\n# Links & Resources\n\n* **Repository:** [github.com/chinmay-sawant/gopdfsuit](https://github.com/chinmay-sawant/gopdfsuit)\n* **Python Integration Examples:** [Python Examples Folder](https://github.com/chinmay-sawant/gopdfsuit/tree/master/sampledata/python)\n* **Validation:** You can validate the output using **OctoPDF** or **veraPDF** to confirm compliance.\n\nIf you find this useful, a **Star** on GitHub is much appreciated! I'm happy to answer any questions about the architecture or implementation."}
{"instruction": "doc2dict: open source document parsing", "input": "", "output": "doc2dict: open source document parsing\n**What My Project Does**\n\nProcesses documents such as html, text, and pdf files into machine readable dictionaries.\n\nFor example, a table:\n\n    \"158\": {\n          \"title\": \"SECURITY OWNERSHIP OF CERTAIN BENEFICIAL OWNERS\",\n          \"class\": \"predicted header\",\n          \"contents\": {\n            \"160\": {\n              \"table\": {\n                \"title\": \"SECURITY OWNERSHIP OF CERTAIN BENEFICIAL OWNERS\",\n                \"data\": [\n                  [\n                    \"Name and Address of Beneficial Owner\",\n                    \"Number of Shares\\nof Common Stock\\nBeneficially Owned\",\n                    \"\",\n                    \"Percent\\nof\\nClass\"\n                  ],...\n\n**Visualizations**\n\n[Original Document](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*X7vMZwJlH-7IG0JEF-x9Sw.png), [Parsed Document Visualization](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*Y8mCK2rEAPNvaSDU6qDiOg.png), [Parsed Table Visualization](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*J5q3W_Krmws6Uov5OIbYFg.png)\n\n**Installation**\n\n    pip install doc2dict\n\n**Basic Usage**\n\n    from doc2dict import html2dict, visualize_dict\n\n    # Load your html file\n    with open('apple_10k_2024.html','r') as f:\n        content = f.read()\n\n    # Parse wihout a mapping dict\n    dct = html2dict(content,mapping_dict=None)\n    # Parse using the standard mapping dict\n    dct = html2dict(content)\n\n    # Visualize Parsing\n    visualize_dict(dct)\n\n    # convert to flat form for efficient storage in e.g. parquet\n    data_tuples = convert_dict_to_data_tuples(dct)\n\n    # same as above but in key value form\n    data_tuples_columnar = convert_dct_to_columnar(dct)\n\n    # convert back to dict\n    convert_data_tuples_to_dict(data_tuples)\n\n**Target Audience**\n\nQuants, researchers, grad students, startups, looking to process large amounts of data quickly. Currently it or forks are used by quite a few companies.\n\n**Comparison**\n\nThis is meant to be a \"good enough\" approach, suitable for scaling over large workloads. For example, Reducto and Hebbia provide an LLM based approach. They recently marked the milestone of parsing 1 billion pages total.\n\ndoc2dict can parse 1 billion pages running on your personal laptop in \\~2 days. I'm currently looking into parsing the entire SEC text corpus (10tb). Seems like AWS Batch Spot can do this for \\~$0.20.\n\n**Performance**\n\nUsing multithreading parses \\~5000 pages per second for html on my personal laptop (CPU limited, AMD Ryzen 7 6800H).\n\nI've prioritized adding new features such as better table parsing. I plan to rewrite in Rust and improve workflow. Ballpark 100x improvement in the next 9 months.\n\n**Future Features**\n\nPDF parsing accuracy will be improved. Support for scans / images in the works.\n\n**Integration with SEC Corpus**\n\nI used the SEC Corpus (\\~16tb total) to develop this package. This package has been integrated into my SEC package: [datamule](https://github.com/john-friedman/datamule-python). It's a bit easier to work with.\n\n    from datamule import Submission\n\n\n    sub = Submission(url='https://www.sec.gov/Archives/edgar/data/320193/[PHONE]/[PHONE]-000145.txt')\n    for doc in sub:\n        if doc.type == '10-K':\n            # view\n            doc.visualize()\n            # get dictionary\n            doc.data\n\n**GitHub Links**\n\n* [doc2dict](https://github.com/john-friedman/doc2dict)\n* [datamule](https://github.com/john-frie"}
{"instruction": "Best Python approach for extracting structured financial data from inconsistent PDFs?", "input": "", "output": "Best Python approach for extracting structured financial data from inconsistent PDFs?\nHi everyone,\n\nI'm currently trying to design a Python pipeline to extract structured financial data from annual accounts provided as PDFs. The end goal is to automatically transform these documents into structured financial data that can be used in valuation models and financial analysis.\n\nThe intended workflow looks like this:\n\n1. Upload one or more **PDF annual accounts**\n2. Automatically detect and extract the **balance sheet and income statement**\n3. Identify **account numbers and their corresponding amounts**\n4. Convert the extracted data into a **standardized chart of accounts structure**\n5. Export everything into a **structured format** (Excel, dataframe, or database)\n6. Run validation checks such as **balance sheet equality and multi-year comparisons**\n\nThe biggest challenge is that the PDFs are **very inconsistent in structure**.\n\nIn practice I encounter several types of documents:\n\n**1. Text-based PDFs**\n\n* Tables exist but are often poorly structured\n* Columns may not align properly\n* Sometimes rows are broken across lines\n\n**2. Scanned PDFs**\n\n* Entire document is an image\n* Requires OCR before any parsing can happen\n\n**3. Layout variations**\n\n* The position of the balance sheet and income statement changes\n* Table structures vary significantly\n* Labels for accounts can differ slightly between documents\n* Columns and spacing are inconsistent\n\nSo the pipeline needs to handle:\n\n* **Text extraction for normal PDFs**\n* **OCR for scanned PDFs**\n* **Table detection**\n* **Recognition of account numbers**\n* **Mapping to a predefined chart of accounts**\n* **Handling multi-year data**\n\nMy current thinking for a Python stack is something like:\n\n* `pdfplumber` or `PyMuPDF` for text extraction\n* `pytesseract` \\+ `opencv` for OCR on scanned PDFs\n* `Camelot` or `Tabula` for table extraction\n* `pandas` for cleaning and structuring the data\n* Custom logic to detect account numbers and map them\n\nHowever, I'm not sure if this is the most robust approach for **messy real-world financial PDFs**.\n\nSome questions I’m hoping to get advice on:\n\n* What Python tools work best for **reliable table extraction in inconsistent PDFs**?\n* Is it better to **run OCR first on every PDF**, or detect whether OCR is needed?\n* Are there libraries that work well for **financial table extraction specifically**?\n* Would you recommend a **rule-based approach** or something more **ML-based** for recognizing accounts and mapping them?\n* How would you design the **overall architecture** for this pipeline?\n\nAny suggestions, libraries, or real-world experiences would be very helpful.\n\nThanks!"}
{"instruction": "Talks from the PyCon US Typing Summit - Intersections, Tensor Shapes, and more!", "input": "", "output": "Talks from the PyCon US Typing Summit - Intersections, Tensor Shapes, and more!\nNormally typing summits aren't recorded & uploaded to YT on the official PyCon channel, so they're lost forever after the conference. This year, the Pyrefly team (with permission) made some unofficial recordings of the talks, since we figured it would be interesting to the broader community.\n\n| Talk | Speaker | Slides | Video |\n|------|---------|--------|-------|\n| Type Checking in Agentic Workflows | Conner Nilsen | [Slides](https://drive.google.com/file/d/1dUQPGxaV_9kN7ulOr01ojg0AOOu-Gf9L/view?usp=sharing) [Transcript](https://pyrefly.org/blog/type-checking-agentic-workflows/) | [Video](https://www.youtube.com/watch?v=xNaKm4fTFtw) |\n| Constraint sets in ty | Douglas Creager | [Slides](https://media.dcreager.net/dcreager-typing-summit-2026-slides.pdf) | [Video](https://www.youtube.com/watch?v=eF_f1uvUn_Q) |\n| From Soundness to Blame: Formalizing Python typing in Lean | Jia Chen | [Slides](https://drive.google.com/file/d/1oFFP-33HPOIpqjq9vjbdCjfMVWMnlmEA/view?usp=sharing) | [Video](https://www.youtube.com/watch?v=ZIPaeEvmhv4) |\n| Tensor Shapes in Pyrefly | Avik Chaudhuri | [Slides](https://drive.google.com/file/d/13l3c0IKCtELt2kOa7mVU6ySolrJZTBFB/view?usp=sharing) [Transcript](https://pyrefly.org/blog/tensor-shapes-in-the-type-system/) | [Video](https://www.youtube.com/watch?v=HE5EyQW_7eY) |\n| Intersection types and more | Jelle Zijlstra | [Slides](https://docs.google.com/presentation/d/1YJZzMR5HYk63whZwpAAoTj10szXI1EqU/edit?usp=sharing&ouid=110553750930042060713&rtpof=true&sd=true) | [Video](https://www.youtube.com/watch?v=xUsPD7iwETY) |\n| PEP 827: Type Manipulation | Michael J. Sullivan | [Slides](https://drive.google.com/file/d/1QsnW6LII_j_HojNTyRApMcdbshgA9l84/view?usp=sharing) | [Video](https://www.youtube.com/watch?v=DP5kcPPedO4) |\n| Thoughts on Python Typing | Guido van Rossum | [Slides](https://gvanrossum.github.io//typingtalk.html) | [Video](https://www.youtube.com/watch?v=_SRFZODQtxw) |\n| Typing Council Updates and Q&A | Carl Meyer, Rebecca Chen, Jelle Zijlstra | [Slides](https://drive.google.com/file/d/19mzgTcwah71p3awG7PVBMixS81xC3Dut/view?usp=sharing) | [Video](https://www.youtube.com/watch?v=A849-uBB3RU) |\n\nView the [Full Playlist](https://youtube.com/playlist?list=PLzsIbngjcN8dlv4jTd7_hAO2t0Kfxzmes) on youtube."}
{"instruction": "Polars code runs slower on 128-core EC2", "input": "", "output": "Polars code runs slower on 128-core EC2\nDisclaimer: I am not sure this post is appropriate for r/LearnPython since it's not a question of \"how to do something in Python\", rather I am looking for a lower-level discussion for why my Python application performs poorly on a significantly more powerful server. Hence I'm posting it here.\n\nThe problem:\n\nI have a relatively complex data pipeline that is written in Polars. On my local machine with 12 cores, the pipeline finishes in about 1200ms. On my 128-core EC2, it takes 13000ms to complete. I have tried setting the POLARS\\_MAX\\_THREADS parameter to 12 on the EC2, and it's still slower.\n\nI am using a TMPFS partition on both machines to read the data into the pipeline directly from RAM. Both my machine and the EC2 have DDR5 RAM so I think they should be comparable.\n\n\nAnyone have any ideas why the pipeline would run much slower on the EC2?"}
{"instruction": "Built a tiny python tool that tells you and your friend where to look to face each other", "input": "", "output": "Built a tiny python tool that tells you and your friend where to look to face each other\n**What My Project Does**\nThis project tells you and your friend which direction to look so you’re technically facing each other, even if you’re in different cities. It takes latitude and longitude for two people and outputs the compass bearings for both sides. You can’t actually see anything, but the math checks out.\n\n**Target Audience**\nThis is just a fun learning project. It’s not meant for production or real-world use. I built it to practice python basics like functions, user input, and some trigonometry, and because the idea itself was funny.\n\n**Comparison**\nUnlike map or navigation apps that calculate routes, distances, or directions to travel, this project only calculates mutual compass bearings. It doesn’t show maps, paths, or visibility. It’s intentionally simple and kind of useless in a fun way.\n\n[https://github.com/Eraxty/Long-Distance-Contact-](https://github.com/Eraxty/Long-Distance-Contact-)"}
{"instruction": "I built a duplicate photo detector that safely cleans 50k+ images using perceptual hashing & cluster", "input": "", "output": "I built a duplicate photo detector that safely cleans 50k+ images using perceptual hashing & cluster\nOver the years my photo archive exploded (multiple devices, exports, backups, messaging apps, etc.). I ended up with thousands of subtle duplicates — not just identical files, but resized/recompressed variants.\n\n \n\nManual cleanup is risky and painful. So I built a tool that:\n\n\\-      Uses SHA-1 to catch byte-identical files\n\n\\-      Uses multiple perceptual hashes (dHash, pHash, wHash, optional colorhash)\n\n\\-      Applies corroboration thresholds to reduce false positives\n\n\\-      Uses Union–Find clustering to group duplicate “families”\n\n\\-      Deterministically selects the highest-quality version\n\n\\-      Never deletes blindly (dry-run + quarantine + CSV audit)\n\n \n\nSome implementation decisions I found interesting:\n\n\\-      Bucketed clustering using hash prefixes to reduce comparisons\n\n\\-      Borderline similarity requires multi-hash agreement\n\n\\-      Exact and perceptual passes feed into the same DSU\n\n\\-      OpenCV Laplacian variance for sharpness ranking\n\n\\-      Designed to be explainable instead of ML-black-box\n\n \n\nPerformance:\n\n\\-      \\~4,800 images → \\~60 seconds hashing (CPU only)\n\n\\-      Clustering \\~2,000 buckets\n\n\\-      Resulted in 23 duplicate clusters in a test run\n\nCurious if anyone here has taken a different approach (e.g. ANN, FAISS, deep embeddings) and what tradeoffs you found worth it."}
{"instruction": "FluxQueue: a lightweight task queue for Python written in Rust", "input": "", "output": "FluxQueue: a lightweight task queue for Python written in Rust\n# What My Project Does\n\nIntroducing **FluxQueue**, a fast and lightweight task queue written in Rust.\n\nFluxQueue makes it easy to define and run background tasks in Python. It supports both synchronous and asynchronous functions and is built with performance and simplicity in mind.\n\n# Target Audience\n\nThis is an early-stage project.\n\nIt’s aimed at developers who want something lighter and faster than Celery or RQ, without a lot of configuration or moving parts. The current release is mainly for testing, experimentation, and feedback rather than large-scale production use.\n\nAt the moment it only supports **Linux**. Windows and macOS support are planned.\n\n# Comparison\n\nCompared to Celery or RQ, it:\n\n* uses **significantly less memory**\n* has **far fewer dependencies**\n* avoids large Python runtime overhead by using a **Rust core for task execution**\n\nIt currently doesn’t include features like scheduling, but those and many more features are planned for future releases.\n\n\nGithub repository: [https://github.com/CCXLV/fluxqueue](https://github.com/CCXLV/fluxqueue)"}
{"instruction": "101 Polars exercises that run in the browser — no setup, just click Run", "input": "", "output": "101 Polars exercises that run in the browser — no setup, just click Run\nWe run Machine Learning Plus and a few years ago we published 101 pandas exercises. It became one of our most visited posts ever.\n\nPeople kept asking for a Polars version. So here it is!\n\nSame format — 101 exercises, progressive difficulty, expected output for each one, hidden solutions you can toggle. But this time everything runs directly in the browser. No pip install. No Colab. Just write your solutions, click Run and it executes on the page.\n\nThe first 40 cover the basics — Series, filtering, dates, null handling, pivots. If you know pandas you'll move through these fast.\n\nThe back half is where it gets interesting. I'll leave that part for you to explore.\n\nWe didn't just translate pandas syntax to Polars. The exercises are written to be idiomatic — expressions instead of apply, over() instead of transform, lazy eval, struct/unnest. The patterns that make Polars worth switching to.\n\nLink to the post: [https://machinelearningplus.com/python/101-polars-exercises-python/](https://machinelearningplus.com/python/101-polars-exercises-python/)\n\nWe'd like to add more based on what people want to practice. Look forward to your feedback!"}
{"instruction": "What frustrates you the most about Python Development", "input": "", "output": "What frustrates you the most about Python Development\nHi there,\n\n\nI wondering what frustrates developers the most when developing software with Python.\n\nI am currently doing my Masters in Computer Science and as part of my project I am doing a very simple survey about the usual Python development lifecycle. I am basically trying to find out what the main friction points are for Python Developers and I am simultaneously developing a tool to address those friction points . It just takes a 2-3 minutes and every response is greatly appreciated.\n\nYou can find the survey at: [Microsoft Forms](https://forms.cloud.microsoft/e/f6psZH6LEm)"}
{"instruction": "Nathan Goldbaum Interviewed about the Move to Free Threading and its Implementation", "input": "", "output": "Nathan Goldbaum Interviewed about the Move to Free Threading and its Implementation\nhttps://alexalejandre.com/interviews/interview-with-nathan-goldbaum/\n\nAfter a lot of effort, the free threading build works but there is still much community work, making packages compatible etc."}
{"instruction": "I built a CLI that turns documents into knowledge graphs — no code, no database", "input": "", "output": "I built a CLI that turns documents into knowledge graphs — no code, no database\nI built sift-kg, a Python CLI that converts document collection into browsable knowledge graphs.\n\npip install sift-kg\n\nsift extract ./docs/\n\nsift build\n\nsift view\n\nThat's the whole workflow. No database, no Docker, no code to write.\n\nI built this while working on a forensic document analysis platform for Cuban property restitution cases. Needed a way to extract entities and relations from document dumps and get a browsable knowledge graphs without standing up infrastructure.\n\nBuilt in Python with Typer (CLI), NetworkX (graph), Pydantic (models), LiteLLM (multi-provider LLM support — OpenAI, Anthropic, Ollama), and pyvis (interactive visualization). Async throughout with rate limiting and concurrency controls.\n\nHuman-in-the-loop entity resolution — the LLM proposes merges, you approve or reject via YAML or interactive terminal review.\n\nThe repo includes a complete FTX case study (9 articles → 373 entities, 1,184 relations). Explore the graph live: [https://juanceresa.github.io/sift-kg/graph.html](https://juanceresa.github.io/sift-kg/graph.html)\n\n\\*\\*What My Project Does\\*\\*                                                                                                                                sift-kg is a Python CLI that extracts entities and relations from document collections using LLMs, builds a knowledge graph, and lets you explore it in an interactive browser-based viewer. The full pipeline runs from the command line — no code to write, no database to set up.\n\n\\*\\*Target Audience\\*\\*\n\nResearchers, journalists, lawyers, OSINT analysts, and anyone who needs to understand what's in a pile of documents without building custom tooling. Production-ready and published on PyPI.\n\n  \\*\\*Comparison\\*\\*\n\nMost alternatives are either Python libraries that require writing code (KGGen, LlamaIndex) or need infrastructure like Docker and Neo4j (Neo4j LLM Graph Builder). GraphRAG is CLI-based but focused on RAG retrieval, not knowledge graph construction. sift-kg is the only pip-installable CLI that goes from documents to interactive knowledge graph with no code and no database.\n\nSource: [https://github.com/juanceresa/sift-kg](https://github.com/juanceresa/sift-kg)  PyPI: [https://pypi.org/project/sift-kg/](https://pypi.org/project/sift-kg/)"}
{"instruction": "Define less, check more: special support for attrs in Pyrefly", "input": "", "output": "Define less, check more: special support for attrs in Pyrefly\nattrs is a package that helps you write classes quickly by automatically generating boilerplate methods like `__init__`.\n\nWhile some of the features from attrs has been standardized in the form of `dataclass` and `dataclass_transform`, dataclasses only support [a subset](https://www.attrs.org/en/stable/why.html#data-classes) of features and attrs is still widely used today.\n\nIt'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:\n1. use Mypy (which implements dedicated attrs support via a plugin)\n2. limit themselves to a subset of the API compatible with `dataclass_transform`\n3. live with limited type checking support\n\nThis 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.\n\nYou can read more about what we added here: https://pyrefly.org/blog/pyrefly-attrs/\n\nThis 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!)"}
{"instruction": "ssrJSON: faster than the fastest JSON, SIMD-accelerated CPython JSON with a json-compatible API", "input": "", "output": "ssrJSON: faster than the fastest JSON, SIMD-accelerated CPython JSON with a json-compatible API\n### What My Project Does\nssrJSON is a high-performance JSON encoder/decoder for CPython. It targets modern CPUs and uses SIMD heavily (SSE4.2/AVX2/AVX512 on x86-64, NEON on aarch64) to accelerate JSON encoding/decoding, including UTF-8 encoding.\n\nOne common benchmarking pitfall in Python JSON libraries is accidentally benefiting from CPython `str` UTF-8 caching (and related effects), which can make repeated dumps/loads of the same objects look much faster than a real workload. ssrJSON tackles this head-on by making the caching behavior explicit and controllable, and by optimizing UTF-8 encoding itself. If you want the detailed background, here is a write-up: [Beware of Performance Pitfalls in Third-Party Python JSON Libraries](https://en.chr.fan/2026/01/07/python-json/).\n\nKey highlights:\n- Performance focus: project benchmarks show ssrJSON is faster than or close to orjson across many cases, and substantially faster than the standard library `json` (reported ranges: `dumps` ~4x-27x, `loads` ~2x-8x on a modern x86-64 AVX2 setup).\n- Drop-in style API: `ssrjson.dumps`, `ssrjson.loads`, plus `dumps_to_bytes` for direct UTF-8 bytes output.\n- SIMD everywhere it matters: accelerates string handling, memory copy, JSON transcoding, and UTF-8 encoding.\n- Explicit control over CPython's UTF-8 cache for `str`: `write_utf8_cache` (global) and `is_write_cache` (per call) let you decide whether paying a potentially slower first `dumps_to_bytes` (and extra memory) is worth it to speed up subsequent `dumps_to_bytes` on the same `str`, and helps avoid misleading results from cache-warmed benchmarks.\n- Fast float formatting via Dragonbox: uses a modified Dragonbox-based approach for float-to-string conversion.\n- Practical decoder optimizations: adopts short-key caching ideas (similar to orjson) and leverages yyjson-derived logic for parts of decoding and numeric parsing.\n\nInstall and minimal usage:\n```bash\npip install ssrjson\n```\n\n```python\nimport ssrjson\n\ns = ssrjson.dumps({\"key\": \"value\"})\nb = ssrjson.dumps_to_bytes({\"key\": \"value\"})\nobj1 = ssrjson.loads(s)\nobj2 = ssrjson.loads(b)\n```\n\n### Target Audience\n- People who need very fast JSON in CPython (especially tight loops, non-ASCII workloads, and direct UTF-8 bytes output).\n- Users who want a mostly `json`-compatible API but are willing to accept some intentional gaps/behavior differences.\n- Note: ssrJSON is beta and has some feature limitations; it is best suited for performance-driven use cases where you can validate compatibility for your specific inputs and requirements.\n\nCompatibility and limitations (worth knowing up front):\n- Aims to match `json` argument signatures, but some arguments are intentionally ignored by design; you can enable a global strict mode (`strict_argparse(True)`) to error on unsupported args.\n- CPython-only, 64-bit only: requires at least SSE4.2 on x86-64 (x86-64-v2) or aarch64; no 32-bit support.\n- Uses Clang for building from source due to vector extensions.\n\n### Comparison\n- Versus stdlib `json`: same general interface, but designed for much higher throughput using C and SIMD; benchmarks report large speedups for both `dumps` and `loads`.\n- Versus orjson and other third-party libraries: ssrJSON is faster than or close to orjson on many benchmark cases, and it explicitly exposes and controls CPython `str` UTF-8 cache behavior to reduce surprises and avoid misleading results from"}
{"instruction": "Fluvel: A modern, reactive UI framework for PySide6 (Beta 1.0)", "input": "", "output": "Fluvel: A modern, reactive UI framework for PySide6 (Beta 1.0)\n*Hello everyone!*\n\nAfter about 8 months of solo development, I wanted to introduce you to **Fluvel**. It is a framework that I built on **PySide6** because I felt that desktop app development in Python had fallen a little behind in terms of ergonomics and modernity.\n\n**Repository**: https://github.com/fluvel-project/fluvel\n\n**PyPI**: https://pypi.org/project/fluvel/\n\n### What My Project Does\n\nWhat makes **Fluvel** special is not just the declarative syntax, but the systems I designed from scratch to make the experience stable and modern:\n\n* **Pyro (Yields Reactive Objects)**: I designed a pure reactivity engine in Python that eliminates the need to manually connect hundreds of signals and slots. With Pyro data models, application state flows into the interface automatically (and vice versa); you modify a piece of data and Fluvel makes sure that the UI reacts instantly, maintaining a decoupled and predictable logic.\n\n* **Real Hot-Reload**: A hot-reload system that allows you to modify the UI, style, and logic of pages in real time without closing the application or losing the current state, as seen in the animated GIF.\n\n* **In-Line Styles**: The QSSProcessor allows defining inline styles with syntax similar to Tailwind (`Button(text=\"Click me!\", style=\"bg[blue] fg[white] p[5px] br[2px]\")`).\n\n* **I18n with Fluml**: A small DSL (Fluvel Markup Language) to handle dynamic texts and translations much cleaner than traditional .ts files.\n\n### Target Audience\n\n* **Python, Web or Mobile developers** who need the power of Qt but are looking for a modern, less verbose workflow.\n* (When stable) **Engineers or scientists** who create complex reactive tools and models that need to be represented visually.\n* **Software architects** who seek to eliminate \"spaghetti code\" from manual signals and have a deterministic, scalable, and maintainable workflow.\n* **Solo developers** who need to build professional-grade desktop apps fast, without sacrificing the native performance and deep control of the Qt ecosystem.\n\n### Comparison / Technical Perspective\n\nIt's important to clarify that **Fluvel is still based on Qt**. It doesn't aim to compete with the raw performance of **PySide6**, since the abstraction layers (reactivity, style processing, context handlers, etc.) inevitably have CPU usage (which has been minimized). Nor does it seek to surpass tools like Flet or Electron in cross-platform flexibility; Fluvel occupies a specific niche: **high-performance native development in terms of runtime, workflows, and project architecture**.\n\n**Why am I sharing it today?**\n\nI know the Qt ecosystem can be verbose and heavy. My goal with Fluvel is for it to be the choice for those who need the power of C++ under the hood, but want to program with the fluidity of a modern framework.\n\nThe project has just entered Beta (v1.0.0b1). I would really appreciate feedback from the community: criticism of Pyro's rules engine, suggestions on the building system, or just trying it out and seeing if you can break it."}
{"instruction": "Pure Python tech stack for modern web development", "input": "", "output": "Pure Python tech stack for modern web development\nI’ve been working as a Python developer for several years and really enjoy the language. Most of my day job involves building desktop tools and working with a Python API for CAD programs. Every now and then, though, I’m asked to build small web apps.\n\nOver time I’ve tried a bunch of different web technologies, but nothing has really clicked for me. I’ve used Python frameworks like Django and Flask, and I’ve also worked with other ecosystems like Laravel and SvelteKit. Right now, my favorite frontend framework is Svelte, and I usually pair it with FastAPI on the backend.\n\nDon’t get me wrong — I think Svelte is awesome. But at the end of the day, it’s still JavaScript. Since Svelte is basically a compiler that turns .svelte files into optimized HTML, CSS, and JS, I started wondering: why isn’t there something like this for Python?\n\nWhat I’m imagining is a truly Python-first, component-based web framework where you could define UI, logic, and even backend interactions in a unified, Pythonic way — and have a compiler handle the rest.\n\nI haven’t really found anything that fits this idea yet.\n\nDo you know of any projects going in this direction?\n\nHave any of you felt the same frustration, or am I just being overly picky about tooling?\n\nI’ve even considered trying to build something like this myself, but that feels like a massive undertaking for one person.\n\nCurious to hear your thoughts..."}
{"instruction": "How has working with other languages and frameworks improved your Python?", "input": "", "output": "How has working with other languages and frameworks improved your Python?\n... I'm making a little push to learn some go at the moment - because of the way my career has come about I've been a bit \"monolingual\" having not really worked in depth in any other languages. So it got me thinking ...\n\nSo... How has your work with... ruby, C, perl, Typescript, rust , fortran  or anything else, improved you as a Python developer?\n\nOr conversely, of course, what bad habits did you bring from those which work poorly in Python?\n\nOr, go the other way - what have you taken from Python that has helped you in another language?"}
{"instruction": "matrixa – a pure-Python matrix library that explains its own algorithms step by step", "input": "", "output": "matrixa – a pure-Python matrix library that explains its own algorithms step by step\n**What My Project Does**\n\nmatrixa is a pure-Python linear algebra library (zero dependencies) built around a custom Matrix type. Its defining feature is verbose=True mode — every major operation can print a step-by-step explanation of what it's doing as it runs:\n\n    from matrixa import Matrix\n\n    A = Matrix([[6, 1, 1], [4, -2, 5], [2, 8, 7]])\n    A.determinant(verbose=True)\n\n    # ─────────────────────────────────────────────────\n    #   determinant()  —  3×3 matrix\n    # ─────────────────────────────────────────────────\n    #   Using LU decomposition with partial pivoting (Doolittle):\n    #   Permutation vector P = [0, 2, 1]\n    #   Row-swap parity (sign) = -1\n    #   U[0,0] = 6  U[1,1] = 8.5  U[2,2] = 6.0\n    #   det = sign × ∏ U[i,i] = -1 × -306.0 = -306.0\n    # ─────────────────────────────────────────────────\n\nSame for the linear solver — A.solve(b, verbose=True) prints every row-swap and elimination step. It also supports:\n\n* dtype='fraction' for exact rational arithmetic (no float rounding)\n* lu\\_decomposition() returning proper (P, L, U) where P @ A == L @ U\n* NumPy-style slicing: A\\[0:2, 1:3\\], A\\[:, 0\\], A\\[1, :\\]\n* All 4 matrix norms: frobenius, 1, inf, 2 (spectral)\n* LaTeX export: A.to\\_latex()\n* 2D/3D graphics transform matrices\n\npip install matrixa [https://github.com/raghavendra-24/matrixa](https://github.com/raghavendra-24/matrixa)\n\n**Target Audience**\n\nStudents taking linear algebra courses, educators who teach numerical methods, and self-learners working through algorithm textbooks. This is NOT a production tool — it's a learning tool. If you're processing real data, use NumPy.\n\n**Comparison**\n\n|matrixa|NumPy|sympy|\n|:-|:-|:-|\n|Dependencies|Zero|C + BLAS|many|\n|verbose step-by-step output|✅|❌|❌|\n|Exact rational arithmetic|✅ (Fraction)|❌|✅|\n|LaTeX export|✅|❌|✅|\n|GPU / large arrays|❌|✅|❌|\n|Readable pure-Python source|✅|❌|partial|\n\nNumPy is faster by orders of magnitude and should be your choice for any real workload. sympy does symbolic math (not numeric). matrixa sits in a gap neither fills: numeric computation in pure Python where you can read the source, run it with verbose=True, and understand what's actually happening. Think of it as a textbook that runs."}
{"instruction": "When scaling application pods with SQLAlchemy pools, who redistributes existing connections?", "input": "", "output": "When scaling application pods with SQLAlchemy pools, who redistributes existing connections?\nI’m running application pods that use SQLAlchemy’s connection pool to connect to PostgreSQL. Each pod has its own pool, so when I scale the application from, say, 3 to 10 replicas, the new pods create new pools while the existing pooled connections remain open.\n\nIf PostgreSQL has read replicas behind a Kubernetes Service or a proxy, I assume new connections might reach the new replicas, but the existing long-lived pooled connections will remain attached to the old replicas.\n\nWho is normally responsible for redistributing those existing connections after scale-out?"}
{"instruction": "I built a Free Python GUI Designer!", "input": "", "output": "I built a Free Python GUI Designer!\nHello everyone! I am a student and a python user. I was recently designing a python app which needed a GUI. I got tired of guessing x and y coordinates and writing endless boilerplate just to get a button centred in a Frame. So, over the last few weeks, I built a visual, drag-and-drop GUI designer that runs entirely in the browser.\n\n**The Tool:**\n- [PyDesigner Website](https://pydesigner.qzz.io/)\n- [Source Code](https://github.com/HasNetwork/PyDesigner)\n\n**What it does:**\n\nMy website is a drag-and-drop GUI designer with live preview. You can export and import projects (json format) and share them, export your build in different GUI frameworks, build and submit templates and widgets. The designer itself has many capabilities such as themes, sizes, properties, etc. It also embeds the image in base64 format for the window icon so that the script is fully portable. I have many more features planned so stay tuned!\n\n**Target Audience:**\n\nPersonal project developers, freelancers or professional GUI builders, everyone can use it for free! The designer has a very simple UI without much of learning curve, so anyone can build their own GUI in minutes.\n\n**How its Different:**\n- **Frameworks:** It supports Tkinter, PyQt5 and CustomTkinter with more coming soon!\n- **Privacy:** Everything happens locally in your browser, using localstorage for caching and saving ongoing projects.\n- **Web Interface:** Easy to use, intuitive, web-based interface with all the options you could ever need!\n- **Clean Code Export:** It generates a proper Python class structure, so you can actually import it into your main logic file.\n- **Documentation:** It has inbuilt documentation with examples for integrating the GUI with your backend logic code.\n- **Asset Embedding:** It converts images to Base64 strings automatically. You don't have to worry about \"file not found\" errors when sharing the script.\n- **Dependencies:** It has zero dependencies other than your chosen GUI framework and Pillow if you use images.\n- **Community:** In-built option to submit community-built templates and widgets.\n\nI know that the modern AI tools can develop a GUI in a single prompt, but you can't really visually edit it with live preview. I’m a student and this is my first real tool, so I’m looking for feedback (specifically on the generated code quality). If you find something unpythonic, let me know so I can fix the compiler😉.\n\n###### Note:  I used AI to polish the English in this post since English isn't my native language. This tool is my personal learning project thus no AI has been used to develop this."}
{"instruction": "argspec: a succinct, type-safe, declarative command line argument parser", "input": "", "output": "argspec: a succinct, type-safe, declarative command line argument parser\n\n[GitHub Repo](https://github.com/lilellia/argspec)・[pypi](https://pypi.org/project/argspec)\n\n## What My Project Does\n\n`argspec` is a declarative, type-driven CLI parser that aims to cast and validate arguments as succinctly as possible without compromising too much on flexibility. Rather than build a parser incrementally, define a dataclass-like\\* schema, which the library uses a [custom type conversion engine](https://github.com/lilellia/typewire) to map `sys.argv[1:]` directly to the class attributes, giving you full IDE support with autocomplete and type inference.\n\n\\* (It actually *is* a dataclass at runtime, even without the `@dataclass` decorator.)\n\n```python\n# backups.py\nfrom argspec import ArgSpec, positional, option, flag\nfrom pathlib import Path\n\nclass Args(ArgSpec):\n    sources: list[Path] = positional(help=\"source directories to back up\", validator=lambda srcs: all(p.is_dir() for p in srcs))\n    destination: Path = option(Path(\"/mnt/backup\"), short=True, validator=lambda dest: dest.is_dir(), help=\"directory to backup files to\")\n\n    max_size: float | None = option(None, aliases=(\"-S\",), help=\"maximum size for files to back up, in MiB\")\n\n    verbose: bool = flag(short=True, help=\"enable verbose logging\")\n    compress: bool = flag(True, help=\"compress the output as .zip\")\n\nargs = Args.from_argv()  # <-- you could also pass Sequence[str] here, but it'll use sys.argv[1:] by default\nprint(args)\n```\n\n```\n$ python backups.py \"~/Documents/Important Files\" \"~/Pictures/Vacation 2025\" -S 1024 --no-compress\nArgs(sources=[PosixPath('~/Documents/Important Files'), PosixPath('~/Pictures/Vacation 2025')], destination=PosixPath('/mnt/backup'), max_size=1024.0, verbose=False, compress=False)\n\n$ python backups.py --help\nUsage:\n    backups.py [OPTIONS] SOURCES [SOURCES...]\n\nOptions:\n    --help, -h\n    Print this message and exit\n\n    true: -v, --verbose\n    enable verbose logging (default: False)\n\n    true: --compress\n    false: --no-compress\n    compress the output as .zip (default: True)\n\n    -d, --destination DESTINATION <Path>\n    directory to backup files to (default: /mnt/backup)\n\n    -S, --max-size MAX_SIZE <float | None>\n    maximum size for files to back up, in MiB (default: None)\n\nArguments:\n    SOURCES <list>\n    source directories to back up\n```\n### Features\n\n- Support positional arguments, options (`-k VALUE`, `--key VALUE`, including the `-k=VALUE` and `--key=VALUE` formats), and boolean flags.\n- Supports automatic casting of the arguments to the annotated types, whether it's a bare type (e.g., `int`), a container type (e.g., `list[str]`), a union type (e.g., `set[Path | str]`), a `typing.Literal` (e.g., `Literal[\"manual\", \"auto\"]).\n- Automatically determines how many arguments should be provided to an argument based on the type hint, e.g., `int` requires one, `list[str]` takes as many as possible, `tuple[str, int, float]` requires exactly three.\n- Argument assignment is non-greedy: `x: list[str] = positional()` followed by `y: str = positional()` will ensure that `x` will leave one value for `y`.\n- Provide default values and (for option/flag) available aliases, e.g., `verbose: bool = flag(short=True)` (gives `-v`), `send: bool = flag(aliases=[\"-S\"])` (gives `-S`).\n- Negator flags (i.e., flags that negate the value of a given flag argument), e.g., `verbose: bool = flag(True, negators=[\"--quiet\"])` (lets `--quiet` unset the verbose variable); for any"}
{"instruction": "v2.0.0 meth: A mathematical expression evaluator.", "input": "", "output": "v2.0.0 meth: A mathematical expression evaluator.\nWhat My Project Does\n\nI have rewrote a math lexer, parser, and interpreter I made before in python. I am really excited as I have just came back from programming after a couple years.\n\nTarget Audience\n\nThis project is meant as a hobby project and to try to learn more about how to make a programming language so I can create one in the future.\n\nComparison\n\nCompared to other projects, meth is simple and easy to use. There isn't any complicated features or quirks. You can find it on github and you can install it from pypi.\n\n```\npip install meth\n```\n\nhttps://github.com/sertdfyguhi/meth\n\nPlease take a look and star! Thanks :)"}
{"instruction": "ruff: no date.today() ?", "input": "", "output": "ruff: no date.today() ?\nThe new version of ruff warns against\n\n`date.today()`\n\npreferring\n\n`datetime.now(ZoneInfo(...))`\n\nWhat do you think about this?  Has date.today() been deprecated due to lack of timezone awareness?"}
{"instruction": "Kreuzberg v4.3.0 and benchmarks", "input": "", "output": "Kreuzberg v4.3.0 and benchmarks\nHi all,\n\nI have two announcements related to [Kreuzberg](https://github.com/kreuzberg-dev/kreuzberg):\n\n1. We released our new [comparative benchmarks](https://kreuzberg.dev/benchmarks). These have a slick UI and we have been working hard on them for a while now (more on this below), and we'd love to hear your impressions and get some feedback from the community!\n2. We released v4.3.0, which brings in a bunch of improvements including PaddleOCR as an optional backend, document structure extraction, and native Word97 format support. More details below.\n\n## What is Kreuzberg?\n\n[Kreuzberg](https://github.com/kreuzberg-dev/kreuzberg) is an open-source (MIT license) polyglot document intelligence framework written in Rust, with bindings for Python, TypeScript/JavaScript (Node/Bun/WASM), PHP, Ruby, Java, C#, Golang and Elixir. It's also available as a docker image and standalone CLI tool you can install via homebrew.\n\nIf the above is unintelligible to you (understandably so), here is the TL;DR: Kreuzberg allows users to extract text from 75+ formats (and growing), perform OCR, create embeddings and quite a few other things as well. This is necessary for many AI applications, data pipelines, machine learning, and basically any use case where you need to process documents and images as sources for textual outputs.\n\n## Comparative Benchmarks\n\nOur new comparative benchmarks UI is live here: https://kreuzberg.dev/benchmarks\n\nThe comparative benchmarks compare Kreuzberg with several of the top open source alternatives - Apache Tika, Docling, Markitdown, Unstructured.io, PDFPlumber, Mineru, MuPDF4LLM. In a nutshell - Kreuzberg is 9x faster on average, uses substantially less memory, has much better cold start, and a smaller installation footprint. It also requires less system dependencies to function (only __optional__ system dependency for it is onnxruntime, for embeddings/PaddleOCR).\n\nThe benchmarks measure throughput, duration, p99/95/50, memory, installation size and cold start with more than 50 different file formats. They are run in GitHub CI on ubuntu latest machines and the results are published into GitHub releases (here is an [example](https://github.com/kreuzberg-dev/kreuzberg/releases/tag/benchmark-run-[PHONE])). The [source code](https://github.com/kreuzberg-dev/kreuzberg/tree/main/tools/benchmark-harness) for the benchmarks and the full data is available in GitHub, and you are invited to check it out.\n\n## V4.3.0 Changes\n\nThe v4.3.0 full release notes can be found here: https://github.com/kreuzberg-dev/kreuzberg/releases/tag/v4.3.0\n\nKey highlights:\n\n1. PaddleOCR optional backend - in Rust. Yes, you read this right, Kreuzberg now supports PaddleOCR in Rust and by extension - across all languages and bindings except WASM. This is a big one, especially for Chinese speakers and other east Asian languages, at which these models excel.\n\n2. Document structure extraction - while we already had page hierarchy extraction, we had requests to give document structure extraction similar to Docling, which has very good extraction. We now have a different but up to par implementation that extracts document structure from a huge variety of text documents - yes, including PDFs.\n\n3. Native Word97 format extraction - wait, what? Yes, we now support the legacy `.doc` and `.ppt` formats directly in Rust. This means we no longer need LibreOffice as an optional system dependency, which saves a lot of space. Who cares you may"}
{"instruction": "Numba in the Browser: Unlocking a New Scientific Python Stack in JupyterLite", "input": "", "output": "Numba in the Browser: Unlocking a New Scientific Python Stack in JupyterLite\nFollowing this [post](https://www.reddit.com/r/Python/comments/1v1x1ps/llvmlite_and_first_step_to_get_numba_in_the/), it's now possible to use Numba directly in your browser in wasm: [https://notebook.link/blog/numba-in-the-browser/](https://notebook.link/blog/numba-in-the-browser/)\nYou can try it here: [https://notebook.link/@anutosh491/numba-ecosystem](https://notebook.link/@anutosh491/numba-ecosystem)"}
{"instruction": "Pymetrica: a new quality analysis tool", "input": "", "output": "Pymetrica: a new quality analysis tool\nHello everyone ! After almost a year and 100 commits into it, I decided to publish to PyPI my new personal tool: ***Pymetrica***.\n\nPyPI page: [https://pypi.org/project/pymetrica/](https://pypi.org/project/pymetrica/)\n\nGithub repository: [https://github.com/JuanJFarina/pymetrica](https://github.com/JuanJFarina/pymetrica)\n\n* **What My Project Does**\n\nPymetrica analyzes Python codebases and generates reports for:\n\n**- Base Stats**: files, folders, classes, functions, LLOC, layers, etc.\n**- ALOC**: “abstract lines of code” (lines representing abstractions/indirections) and its percentage\n**- CC**: Cyclomatic Complexity and its density per LLOC\n**- HV**: Halstead Volume\n**- MC**: Maintainability Cost (a simplified MI-style metric combining complexity and size)\n**- LI**: Layer Instability (coupling between layers)\n**- Architecture Diagram**: layers and modules with dependency arrows (number of imports)\n\nCurrently the tool outputs terminal reports. Planned features include CI/pre-commit integration, additional report formats, and configuration via `pyproject.toml`.\n\n* **Target Audience**\n\n\\- Developers concerned with maintainability\n\\- Tech Leads / Architects evaluating codebases\n\\- Teams analyzing subpackages or layers for refactoring\n\nSince the tool is \"size independent\", you can run the analysis on a whole codebase, on a sublayer, or any lower level module you like.\n\n* **Comparison**\n\nI've been using Radon, SonarQube, Veracode, and Blackduck for some years now, but found their complexity-related metrics not too useful. I love good software designs that allow more maintainability and fast development, as well as sometimes like being more pragmatic and avoid premature abstractions and optimizations. At some point, I realized that if you have 100% code coverage (a typical metric used in CI checks) **and also** abstractions for almost everything in your codebase, you are essentially multiplying by 4 your codebase size. And while I found abstractions nice in general, I don't want to be maintaining 4 times the size of the real production value code.\n\nSo, my first venture for Pymetrica was to get a measure of \"abstractness\". That's where ALOC was born (abstract lines of code) which represent all lines of code that are merely indirections (that is, they will execute code that lives somewhere else). This also includes abstract classes, interfaces, and essentially any class that is never instantiated, among others (function definitions, function calls, etc.). The idea is of course not to go back to a pure structured programming, but to not get too lost in premature abstraction.\n\nShortly after that I started digging in other software metrics, and specially how to deal with \"complexity\". I got to see that most metrics (Cyclomatic Complexity, Halstead Volume, Maintainability Index, Cognitive Complexity, etc.) are not based on \"codebases\" but rather on \"modules\" or \"functions\" scopes, so I decided to implement \"codebase-level\" implementations of those. Also because it never made sense to me that SonarQube's \"Cognitive Complexity\" never flagged any of the horrible codebases I've seen in different projects.\n\nMy goal with Pymetrica is that it can be very **actionable**, that you can see a score and inmediately understand what needs to be done: MC is high ? Is it due to size or raw MC due to high CC and HV ? You can easily know that. And you can easily see if a subpackage (\"layer\") is the main culprit fo"}
{"instruction": "Built a file search engine that understands your documents (with OCR and Semantic Search)", "input": "", "output": "Built a file search engine that understands your documents (with OCR and Semantic Search)\nHey Pythonistas!\n\n# What My Project Does\n\nI’ve been working on **File Brain**, an open-source desktop tool that lets you search your local files using natural language. It runs 100% locally on your machine.\n\n**The Problem:** We have thousands of files (PDFs, Office docs, images, archives, etc) and we constantly forget their filenames (or not named them correctly in the first place). Regular search tools won't save you when you don't use the exact keywords, and they definitely won't understand the *content* of a scanned invoice or a screenshot.\n\n**The Solution:** I built a tool that indexes your files and allows you to perform queries like *\"Airplane ticket\"* or *\"Marketing 2026 Q1 report\"*, and retrieves relevant files even when their filenames are different or they don't have these words in their content.\n\n# Target Audience\n\n**File Brain** is useful for any individual or company that needs to locate specific files containing important information quickly and securely. This is especially useful when files don't have descriptive names (most often, it is the case) or are not placed in a well-organized directory structure.\n\n# Comparison\n\nHere is a comparison between **File Brain** and other popular desktop search apps:\n\n|App Name|Price|OS|Indexing|Search Speed|File Content Search|Fuzzy Search|Semantic Search|OCR|\n|:-|:-|:-|:-|:-|:-|:-|:-|:-|\n|Everything|Free|Windows|No|Instant|No|Wildcards/Regexp|No|No|\n|Listary|Free|Windows|No|Instant|No|Yes|No|No|\n|Alfred|Free|MacOS|No|Very fast|No|Yes|No|Yes|\n|Copernic|25$/yr|Windows|Yes|Fast|170+ formats|Partial|No|Yes|\n|DocFetcher|Free|Cross-platform|Yes|Fast|32 formats|No|No|No|\n|Agent Ransack|Free|Windows|No|Slow|PDF and Office|Wildcards/Regexp|No|No|\n|File Brain|Free|Cross-platform|Yes|Very fast|1000+ formats|Yes|Yes|Yes|\n\n**File Brain** is the only file search engine that has semantic search capability, and the only free option that has OCR built in, with a very large base of supported file formats and very fast results retrieval (typically, under a second).\n\nInterested? Visit the repository to learn more: [https://github.com/Hamza5/file-brain](https://github.com/Hamza5/file-brain)\n\nIt’s currently available for **Windows** and **Linux**. It should work on Mac too, but I haven't tested it yet."}
{"instruction": "State Machine Frameworks?", "input": "", "output": "State Machine Frameworks?\nAt work we find ourselves writing many apps that include a notion of \"workflow.\" In many cases these have grown organically over the past few years and I'm starting to find ways to refactor these things to remove the if/then trees that are hard to follow and reason about.\n\nA lot of what we have are really state machines, and I'd like to begin a series of projects to start cleaning up all the old applications, replacing the byzantine indirection and if/thens with something like declarative descriptions of states and transitions.\n\nOf course, Google tells me that there are quite a few frameworks in this domain and I'd love to see some opinions from y'all about the strengths of projects like \"python-statemachine,\" \"transitions\" and \"statesman\". We'll need something that plays well with both sync and async code and is relatively accessible even for those without a computer science background (lots of us are geneticists and bioinformaticists)."}
{"instruction": "justx - An interactive command library for your terminal, powered by just", "input": "", "output": "justx - An interactive command library for your terminal, powered by just\n# What My Project Does\n\n[justx](https://github.com/casey/just) is an interactive terminal wrapper for [just](https://github.com/casey/just). The main thing it adds is an interactive TUI to browse, search, and run your recipes. On top of that, it supports multiple global justfiles (`~/.justx/git.just`, `docker.just`, …) which lets you easily build a personal command library accessible from anywhere on your system.\n\nA quick demo can be seen [here](https://fpgmaas.github.io/justx/).\n\nTry it out with:\n\n    uv tool install justx\n    justx init --download-examples\n    justx\n\n# Target Audience\n\nDevelopers who want a structured way to organize and run their commonly used commands across the system.\n\n# Comparison\n\n* **just** itself has no TUI and limited global recipe management. `justx` adds a TUI on top of just, and brings improved capability for global recipes by allowing users to place multiple files in the `~/.justx` directory.\n\n# Learn More\n\n* GitHub: [fpgmaas/justx](https://github.com/fpgmaas/justx)\n* Docs: [fpgmaas.github.io/justx](https://fpgmaas.github.io/justx/)"}
{"instruction": "FREE python lessons taught by Boston University students!", "input": "", "output": "FREE python lessons taught by Boston University students!\nHi everyone! \n\nMy name is Wynn and I am a member of Boston University’s Girls Who Code chapter. My friend, Molly, and I would like to inform you all of a **free coding program** we are running for students of all genders from 3rd-12th grade. The **Bits & Bytes program** is a great opportunity for students to learn how to code, or improve their coding skills. Our program runs on Zoom on Saturdays for 1 hour starting **March 21st** and ending on **April 25th** (6-week) from 11:00 am to 12:00 pm. Each lesson will be taught by Boston University students, many of whom are Computer Science (or adjacent) majors themselves.\n\nFor Bits (3rd-5th grade), students will learn the basics of computer science principles through MIT-created learning platform Scratch and learn to transfer their skills into the Python programming language. Bits allows young students to learn basic coding skills in a fun and interactive way!\n\nFor Bytes (6th-12th grade), students will learn computer science fundamentals in Python such as loops, functions, and recursion and use these skills during lessons and assignments. Since much of what we go over is similar to what an intro level college computer science class would cover, this is a great opportunity to prepare students for AP Computer Science or a degree in computer science!\n\nWe would love for you to apply or share with anyone interested! Unfortunately, I can not include an image of our flyer or link to our google form to apply to this post, but here is a link to a GitHub repo that includes that information: [https://github.com/WynnMusselman/GWC-Bits-Bytes-2026-Student-Application](https://github.com/WynnMusselman/GWC-Bits-Bytes-2026-Student-Application)\n\nIf you have any more questions, feel free to email [[EMAIL]](mailto:[EMAIL]), message @ gwcbostonu on Facebook or Instagram, leave a comment, or message me.\n\nWe're eagerly looking forward to another season of coding and learning with the students this spring!"}
{"instruction": "scientific_pydantic: Pydantic adapters for common scientific data types", "input": "", "output": "scientific_pydantic: Pydantic adapters for common scientific data types\nCode: [https://github.com/psalvaggio/scientific\\_pydantic](https://github.com/psalvaggio/scientific_pydantic)\n\nDocs: [https://psalvaggio.github.io/scientific\\_pydantic/latest/](https://psalvaggio.github.io/scientific_pydantic/latest/)\n\n**What My Project Does**\n\nThis project integrates a number of common scientific data types into \\`pydantic\\`. It uses the \\`Annotated\\` pattern for integrating third-party types with adapter objects. For example:\n\n\\`\\`\\`python\nimport typing as ty\nimport astropy.units as u\nimport pydantic\nfrom scientific\\_pydantic.astropy.units import QuantityAdapter\n\nclass Points(pydantic.BaseModel):\npoints: ty.Annotated\\[u.Quantity, QuantityAdapter(u.m, shape=(None, 3), ge=0)\\]\n\\`\\`\\`\nwould define a model with a field that is an N x 3 array of points with non-negative XYZ in spatial units equivalent to meters.\n\nNo need for \\`arbitrary\\_types\\_allowed=True\\` and with the normal \\`pydantic\\` features of JSON serialization and conversions.\n\nI currently have adapters for \\`numpy\\` (\\`ndarray\\` and \\`dtype\\`), \\`scipy\\` (\\`Rotation\\`), \\`shapely\\` (geometry types) and \\`astropy\\` (\\`UnitBase\\`, \\`Quantity\\`, \\`PhysicalType\\` and \\`Time\\`), along with some stuff from the standard library that \\`pydantic\\` doesn't ship with (\\`slice\\`, \\`range\\`, \\`Ellipsis\\`).\n\n**Target Audience**\n\nUsers of both \\`pydantic\\` and common scientific libraries like: \\`numpy\\`, \\`scipy\\`, \\`shapely\\` and \\`astropy\\`.\n\n**Comparison**\n\n[https://pypi.org/project/pydantic-numpy/](https://pypi.org/project/pydantic-numpy/)\n\nMy project offers a few additional built-in features, such as more powerful shape specifiers, bounds checking and clipping. I don't support custom serialization, but this is just the first version of my project, that's on my list of future features.\n\n[https://pypi.org/project/pydantic-shapely/](https://pypi.org/project/pydantic-shapely/)\n\nThis is pretty similar in scope. My project does WKT parsing in addition to GeoJSON and also offers coordinate bounds. Not a game-changer.\n\nI don't know of anything else that offers \\`scipy\\` \\`Rotation\\` or \\`astropy\\` adapters."}
{"instruction": "Writing Matematically correct Numerical Code", "input": "", "output": "Writing Matematically correct Numerical Code\nI contribute to SciPy and kept running into a class of bug that annoys me: the outputs look plausible, the tests pass, but the equation the code implements is subtly wrong. So I've been building a tracer that runs Python/NumPy code and hands back whatever mathematics it actually computed, as a SymPy expression you can simplify or differentiate like anything else.\n\nIt's been more useful than I expected. Comparing an implementation against the formula in a paper, catching two functions that agree on my test data but turn out to compute different things, digging up the inputs my tests never hit (ties, zero denominators). It traces real library code too, most of numpy and a good chunk of scipy, scikit-learn, statsmodels, cvxpy. The repo is \\`aadya940/scikit-verify\\` linked in the comments along with a blog post.\n\nStill rough in places, would genuinely like feedback. There may be other better solutions, happy to hear them as well!"}
{"instruction": "Does Python code tend to be more explicit than other alternatives?", "input": "", "output": "Does Python code tend to be more explicit than other alternatives?\nFor example, Java and C# are full of enterprise coding styles, OOP and design patterns. For me, it's a nightmare to navigate and write code that way at my workplace. But whenever I read Python code or I read online lessons about it, the code is more often than not less abstracted, more explicit and there's overall less ceremony. No interfaces, no dependency injection, no events... mostly procedural, data-oriented and lightly OOP code.\n\nI was wondering, is this some real observation or it's just my lack of experience with Python? Thank you!"}
{"instruction": "An open-source tool to add \"Word Wise\" style definitions to any EPUB using Python", "input": "", "output": "An open-source tool to add \"Word Wise\" style definitions to any EPUB using Python\nI've been trying to read more English books, but constantly stopping to look up difficult words breaks my flow. I really liked Kindle's \"Word Wise\" feature, but it doesn't work on sideloaded books or other e-readers like Kobo.\n\nSo, I built Sura. It's a Python tool that injects ruby text definitions directly into EPUB files.\n\nRepo: [https://github.com/watsuyo/Sura](https://github.com/watsuyo/Sura)\n\n\\## What My Project Does\n\nSura processes EPUB files to help language learners read more smoothly. Specifically, it:\n\n1. Extracts text from an EPUB file.\n\n2. Filters words based on difficulty using wordfreq (Zipf scores), so it only targets words you likely don't know.\n\n3. Generates definitions using an LLM (OpenAI/compatible API) to provide short, context-aware meanings.\n\n4. Injects ruby text (HTML/CSS) back into the EPUB structure.\n\n5. Rebuilds the EPUB, making it compatible with almost any e-reader (Kobo, Kindle, etc.).\n\nIt uses asyncio for concurrent processing to keep performance reasonably fast.\n\n\\## Target Audience\n\nThis tool is meant for language learners who want to read native content without constant dictionary interruptions, and e-reader users (Kobo/Kindle) who sideload their books.\n\nIt is currently a hobby/open-source project intended for personal use and for developers interested in EPUB manipulation or LLM integration.\n\n\\## Comparison\n\nThe main alternative is Kindle's native \"Word Wise\" feature.\n\nKindle Word Wise: Only works on books purchased directly from Amazon. It does not support sideloaded documents or other devices like Kobo.\n\nSura: Works on any DRM-free EPUB file, allowing you to use the feature on sideloaded books and non-Kindle devices. It also allows for customizable difficulty thresholds, unlike the fixed settings on Kindle."}
{"instruction": "Servy 4.9 released, Turn any Python app into a native Windows service", "input": "", "output": "Servy 4.9 released, Turn any Python app into a native Windows service\nIt's been five months since the announcement of Servy, and Servy 4.9 is finally here.\n\nThe community response has been amazing: 1,000+ stars on GitHub and 15,000+ downloads.\n\nIf you haven't seen Servy before, it's a Windows tool that turns any Python app (or other executable) into a native Windows service. You just set the Python executable path, add your script and arguments, choose the startup type, working directory, and environment variables, configure any optional parameters, click install, and you're done. Servy comes with a desktop app, a CLI, PowerShell integration, and a manager app for monitoring services in real time.\n\nIn this release (4.9), I've added/improved:\n\n* Added live CPU and RAM performance graphs for running services\n* Encrypt environment variables and process parameters for maximum security\n* Include SBOMs in release artifacts for provenance\n* Added dark mode support to installers\n* New GUI and PowerShell module enhancements and improvements\n* Detailed documentation\n* Bug fixes\n\nCheck it out on GitHub: [https://github.com/aelassas/servy](https://github.com/aelassas/servy)\n\nDemo video here: [https://www.youtube.com/watch?v=biHq17j4RbI](https://www.youtube.com/watch?v=biHq17j4RbI)\n\nPython sample: [Examples & Recipes](https://github.com/aelassas/servy/wiki/Examples-&-Recipes#run-a-python-script-as-a-service)"}
{"instruction": "A folder-native photo manager in Python/Qt optimized for TB-scale libraries", "input": "", "output": "A folder-native photo manager in Python/Qt optimized for TB-scale libraries\n# What My Project Does\n\nThis project is a **local-first, folder-native photo manager** written primarily in **Python**, with a **Qt (PySide6)** desktop UI.\n\nInstead of importing photos into a proprietary catalog, it treats **existing folders as albums** and keeps all original media files untouched. All metadata and user decisions (favorites, ordering, edits) are stored either in lightweight sidecar files or a **single global SQLite index**.\n\nThe core focus of the project is **performance and scalability** for very large local photo libraries:\n\n* A global SQLite database indexes all assets across the library\n* Indexed queries enable instant sorting and filtering\n* Cursor-based pagination avoids loading large result sets into memory\n* Background scanning and thumbnail generation prevent UI blocking\n\nThe current version is able to handle **TB-scale libraries with hundreds of thousands of photos** while keeping navigation responsive.\n\n# Target Audience\n\nThis project is intended for:\n\n* Developers and power users who manage **large local photo collections**\n* Users who prefer **data ownership and transparent storage**\n* People interested in **Python + Qt desktop applications** with non-trivial performance requirements\n\nThis is **not a toy project**, but rather an **experimental project**.\nIt is actively developed and already usable for real-world libraries, but it has **not yet reached the level of long-term stability or polish expected from a fully mature end-user application**.\n\nSome subsystems—especially caching strategies, memory behavior, and edge-case handling—are still evolving, and the project is being used as a platform to explore design and performance trade-offs.\n\n# Comparison\n\nCompared to common alternatives:\n\n* **File explorers (Explorer / Finder)**\n   * Simple and transparent − Become slow and repeatedly reload thumbnails for large folders\n* **Catalog-based photo managers**\n   * Fast browsing and querying − Require importing files into opaque databases that are hard to inspect or rebuild\n\nThis project aims to sit in between:\n\n* Folder-native like a file explorer\n* Database-backed like a catalog system\n* Fully rebuildable from disk\n* No cloud services, no AI models, no proprietary dependencies\n\nArchitecturally, the most notable difference is the **hybrid design**:\nplain folders for storage + a global SQLite index for performance.\n\n# Looking for Feedback\n\nAlthough the current implementation already performs well on TB-scale libraries, there is still room for optimization, especially around:\n\n* Thumbnail caching strategies\n* Memory usage during large-grid scrolling\n* SQLite query patterns and batching\n* Python/Qt performance trade-offs\n\nI would appreciate feedback from anyone who has worked on or studied **large Python or Qt desktop applications**, particularly photo or media managers.\n\n# Repository\n\nGitHub:\n[https://github.com/OliverZhaohaibin/iPhotos-LocalPhotoAlbumManager](https://github.com/OliverZhaohaibin/iPhotos-LocalPhotoAlbumManager)\n\n#"}
{"instruction": "PyNear 2.5 is out — exact & binary k-NN for Python: 13× faster than Faiss brute force below 256-D", "input": "", "output": "PyNear 2.5 is out — exact & binary k-NN for Python: 13× faster than Faiss brute force below 256-D\n  I maintain PyNear, a C++17/pybind11 nearest-neighbour library for Python (pip install pynear, NumPy is the only dependency). One API for the three regimes that usually need three different tools:\n\n  \\- Exact search — VP-trees for L2/L1/L∞/cosine, BK-tree for Hamming range queries. True nearest neighbours, no recall knob.\n\n  \\- Binary descriptors (ORB, BRIEF, perceptual hashes, SimHash) — Multi-Index Hashing with a pigeonhole guarantee: every neighbour within your Hamming radius is found. Plus binary IVF and binary HNSW.\n\n  \\- Float ANN — HNSW (including an int8-quantised variant with \\~4× less RAM) and IVF-Flat.\n\n  Version 2.5 just shipped after a performance pass over every index in the library, and I re-benchmarked everything against Faiss on a 24-core machine.\n\n  Where PyNear beats Faiss (measured fairly — see the gotcha below):\n\n  ┌───────────────────────────────────────────────────┬──────────────────────────┬───────────────────────────────┬────────────────┐\n\n  │                     Workload                      │          PyNear          │             Faiss             │    Speedup     │\n\n  ├───────────────────────────────────────────────────┼──────────────────────────┼───────────────────────────────┼────────────────┤\n\n  │ Exact float k-NN, 2.5M × 16-D                     │ 0.86 ms / 16-query batch │ 11.4 ms (IndexFlatL2)         │ 13×, and exact │\n\n  ├───────────────────────────────────────────────────┼──────────────────────────┼───────────────────────────────┼────────────────┤\n\n  │ Exact float k-NN, 120k × 128-D                    │ 0.49 ms                  │ 5.7 ms                        │ 12×            │\n\n  ├───────────────────────────────────────────────────┼──────────────────────────┼───────────────────────────────┼────────────────┤\n\n  │ 512-bit near-duplicates, 1M codes, 100% Recall@10 │ 114,039 QPS              │ 3,341 QPS (IndexBinaryFlat)   │ 34×            │\n\n  ├───────────────────────────────────────────────────┼──────────────────────────┼───────────────────────────────┼────────────────┤\n\n  │ Same workload vs Faiss's own MIH                  │ 114,039 QPS              │ 46 QPS (IndexBinaryMultiHash) │ \\~2,500×        │\n\n  ├───────────────────────────────────────────────────┼──────────────────────────┼───────────────────────────────┼────────────────┤\n\n  │ SIFT1M 128-bit, MIH vs MIH at matched recall      │ —                        │ —                             │ up to 3.5×     │\n\n  ├───────────────────────────────────────────────────┼──────────────────────────┼───────────────────────────────┼────────────────┤\n\n  │ IVF build time, 50k vectors, 128–1024-D           │ 0.37–1.5 s               │ 0.51–3.7 s                    │ 1.4–2.4×       │\n\n  └───────────────────────────────────────────────────┴──────────────────────────┴───────────────────────────────┴────────────────┘\n\n  The story behind the first two rows: below \\~256 dimensions a metric tree prunes while brute force must touch everything. Faiss doesn't ship an exact metric tree, so its exact option is the flat scan — and losing to a pruning structure there is\n\n  expected, not a benchmark trick.\n\n  Where Faiss wins — kept in our README and the PDF report with full numbers, because you should use the right tool: exact binary k-NN (Faiss's batched popcount scan beats our tree at every width, 0.15–0.29 ms vs 3.2–15.9 ms) and raw approximate-L2\n\n  latency at 512–1024-D ("}
{"instruction": "Python 3.14.3 and 3.13.12 are now available!", "input": "", "output": "Python 3.14.3 and 3.13.12 are now available!\nSee [https://pythoninsider.blogspot.com/2026/02/python-3143-and-31312-are-now-available.html](https://pythoninsider.blogspot.com/2026/02/python-3143-and-31312-are-now-available.html)"}
{"instruction": "When did you start caring more about code structure in Python?", "input": "", "output": "When did you start caring more about code structure in Python?\nEarly on I focused on \"does it work?\" more than how clean the code was. Lately I’m starting to care more about readability, structure, and maintainability.\n\nFor those further along:\n\n* when did that shift happen for you?\n* did it come from bigger projects, other people reading your code, or work experience?\n\nInterested in how others evolved here."}
{"instruction": "Community consensus on when to use dataclasses vs non-OO types?", "input": "", "output": "Community consensus on when to use dataclasses vs non-OO types?\nSo, 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.\n\nI'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.\n\nBoth 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.\n\nIf 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).\n\nSo, better to use:\n\nif isinstance(msg,UpdateObject):\n\nor:\n\nif msg\\[0\\] == 'update':\n\n?"}
{"instruction": "I built a decorator-first task scheduler because I was tired of setting up Celery for cron jobs", "input": "", "output": "I built a decorator-first task scheduler because I was tired of setting up Celery for cron jobs\nI kept reaching for Celery + Redis whenever I needed to run a function on a schedule. Daily reports, health checks, cleanup jobs — simple stuff that didn't need distributed infrastructure.\n\nSo I built FastScheduler: a lightweight, decorator-based scheduler with async support, persistence, and an optional real-time dashboard.\n\n# What My Project Does\n\nFastScheduler lets you schedule Python functions using decorators:\n\n    from fastscheduler import FastScheduler\n\n    scheduler = FastScheduler()\n\n    @scheduler.every(10).seconds\n    def heartbeat():\n        print(\"alive\")\n\n    @scheduler.daily.at(\"09:00\", tz=\"America/New_York\")\n    async def morning_report():\n        await send_report()\n\n    @scheduler.cron(\"0 9 * * MON-FRI\")\n    def weekday_task():\n        do_work()\n\n    scheduler.start()\n\nKey features:\n\n* **Decorator-based API** — no config files, intent is clear from the code\n* **Async/await support** — native async function support\n* **Persistence** — state saves to JSON, survives restarts, handles missed jobs\n* **Timezone support** — schedule jobs in any timezone\n* **Cron expressions** — `@scheduler.cron(\"*/15 * * * *\")`\n* **Retries & timeouts** — exponential backoff, kill long-running jobs\n* **Dead letter queue** — track failed jobs for debugging\n* **FastAPI dashboard** — real-time monitoring UI with pause/resume controls\n\n# Target Audience\n\nThis is meant for **production use** in single-application deployments. I use it in production for broadcast automation systems at work.\n\nIt's ideal for:\n\n* Web apps that need background jobs without Celery overhead\n* Scripts that need reliable scheduled execution\n* Services where you want visibility into what's running\n* Anyone who finds themselves writing `while True: sleep(60)` loops\n\nIt's NOT for distributed task queues across multiple workers — use Celery/Dramatiq for that.\n\n# Comparison\n\n|Feature|FastScheduler|Celery|APScheduler|schedule|\n|:-|:-|:-|:-|:-|\n|External dependencies|None|Redis/RabbitMQ|None|None|\n|Async support|✅ Native|✅|✅|❌|\n|Persistence|✅ JSON file|✅ Backend|✅ Optional|❌|\n|Web dashboard|✅ Built-in|❌ (Flower separate)|❌|❌|\n|Decorator API|✅ Clean|❌|❌ Verbose|✅|\n|Cron expressions|✅|✅|✅|❌|\n|Distributed|❌|✅|❌|❌|\n\n**vs Celery:** FastScheduler is for when you don't need distributed workers. No Redis, no message broker, no separate processes.\n\n**vs APScheduler:** Simpler API. APScheduler requires understanding triggers, executors, and job stores. FastScheduler is just decorators.\n\n**vs schedule:** FastScheduler adds async support, persistence, timezone handling, and a dashboard.\n\n# Links\n\n* GitHub: [https://github.com/MichielMe/fastscheduler](https://github.com/MichielMe/fastscheduler)\n* PyPI: `pip install fastscheduler[all]`\n\nI'd love feedback — what features would make this more useful for your projects? Any edge cases I should handle?"}
{"instruction": "GoPdfSuit v5.0.0: A high-performance PDF engine for Python (now on PyPI)", "input": "", "output": "GoPdfSuit v5.0.0: A high-performance PDF engine for Python (now on PyPI)\nI’m excited to share the v5.0.0 release of GoPdfSuit. While the core engine is powered by Go for performance, this update officially brings it into the Python ecosystem with a dedicated PyPI package.\n\nWhat My Project Does\n\nGoPdfSuit is a document generation and processing engine designed to replace manual coordinate-based coding (like ReportLab) with a visual, JSON-based workflow. You design your layouts using a React-based UI and then use Python to inject data into those templates.\n\n**Key Features in v5.0.0:**\n\nOfficial Python Wrapper: Install via pip install pypdfsuit.\n\nAdvanced Redaction: Securely scrub text and links using internal decryption.\n\nTypst Math Support: Render complex formulas using Typst syntax (cleaner than LaTeX) at native speeds.\n\nEnterprise Performance: Optimized hot-paths with a lock-free font registry and pre-resolved caching to eliminate mutex overhead.\n\n**Target Audience**\n\nThis project is intended for production environments where document generation speed and maintainability are critical. It’s ideal for developers who are tired of \"guess-and-check\" coordinate coding and want a more visual, template-driven approach to PDFs.\n\nIt provide the PDF compliance (PDF/UA-2 and PDF/A-4) even if not compliance the performance is just subpar. (You can check the website for performance comparison)\n\n**Comparison**\n\nVs. ReportLab: Instead of writing hundreds of lines of Python to position elements, GoPdfSuit uses a visual designer. The engine logic runs in \\~60ms, significantly outperforming pure Python solutions for heavy-duty document generation.\n\n**How Python is Relevant**\n\nPython acts as the orchestration layer. By using the pypdfsuit library, you can interact with the Go-powered binary or containerized service using standard Python objects. You get the developer experience of Python with the performance of a Go backend.\n\nWebsite - [https://chinmay-sawant.github.io/gopdfsuit/](https://chinmay-sawant.github.io/gopdfsuit/)\n\n**Source Code:**\n\n[https://github.com/chinmay-sawant/gopdfsuit](https://github.com/chinmay-sawant/gopdfsuit)\n\n**Sample python code**\n\n[https://github.com/chinmay-sawant/gopdfsuit/tree/master/sampledata/python/amazonReceipt](https://github.com/chinmay-sawant/gopdfsuit/tree/master/sampledata/python/amazonReceipt)\n\n**Documentation** \\- [https://chinmay-sawant.github.io/gopdfsuit/#/documentation?item=introduction](https://chinmay-sawant.github.io/gopdfsuit/#/documentation?item=introduction)\n\n**PyPI:** pip install pypdfsuit\n\nIf you find this useful, a Star on GitHub is much appreciated! I'm happy to answer any questions about the architecture or implementation."}
{"instruction": "Python Type Checker Comparison: Empty Container Inference", "input": "", "output": "Python Type Checker Comparison: Empty Container Inference\nEmpty containers like [] and {} are everywhere in Python. It's super common to see functions start by creating an empty container, filling it up, and then returning the result.\n\nTake this, for example:\n\n```\ndef my_func(ys: dict[str, int]):\n  x = {}\n  for k, v in ys.items():\n    if some_condition(k):\n      x.setdefault(\"group0\", []).append((k, v))\n    else:\n      x.setdefault(\"group1\", []).append((k, v))\n  return x\n```\n\nThis seemingly innocent coding pattern poses an interesting challenge for Python type checkers. Normally, when a type checker sees `x = y` without a type hint, it can just look at `y` to figure out `x`'s type. The problem is, when y is an empty container (like `x = {}` above), the checker knows it's a `dict`, but has no clue what's going inside.\n\nThe big question is: How is the type checker supposed to analyze the rest of the function without knowing `x`'s type?\n\nDifferent type checkers implement distinct strategies to answer this question. This blog will examine these different approaches, weighing their pros and cons, and which type checkers implement each approach.\n\nFull blog: https://pyrefly.org/blog/container-inference-comparison/"}
{"instruction": "I hate code written by LLMs", "input": "", "output": "I hate code written by LLMs\nHi everyone,\nI am a Data Science student and I am far away from considering myself a \"good coder\", as I think I miss many fundamental concepts and I do not know a lot of standard good practices. Hence, I wanted the opinion from people with greater expertise in the field. Is it only me who hates how LLMs write code? I am not able to understand it properly, and I always have the feeling it is overcomplicating logics and processes that are in actually very simple, making a script 5 times its actual lenght.\n\nI often do group projects with colleagues of mine, which I am now pretty sure do not even check the code the agent writes for them and it is always very frustrating to navigate in the maze of newly created functions and files which always feel redundant and inefficient.\n\nIn particular, I hate these features:\n\\- They tend to go on a newline everytime there is a list of parameters, even when it is not necessary.\n\\- Tthey do not comment nothing and if they do the comments are too long and too technical\n\\- They declare way too many functions. I was thought that the main goal of functions was reusability. What is the purpose of having a function that you only call once? Maybe they even call that function \"run\\_analysis\\_xyz\". What is the purpose of that? Why do you have to prefer a code which is nested and does not execute top to bottom, in the same way that a reader can follow it?\n\\- The variables naming rarely reflct their actual purposes.\n\\- Unecessaries safety checks, that are good for general code but they make no sense\n\nI am starting to hate group projects for this reason. I just get nervous when I try to read code that is clearly generated. Am I wrong for using AI just as an assistant and not as a completely autonomous code writer?"}
{"instruction": "Possible supply-chain attack waiting to happen on Django projects?", "input": "", "output": "Possible supply-chain attack waiting to happen on Django projects?\nI'm working on a side-project and needed to use django-sequences but I accidentally installed \\`django-sequence\\` which worked. I noticed the typo and promptly uninstalled it. I was curious what it was and turns out it is the same package published under a different name by a different pypi account. They also have published a bunch of other django packages. Most likely this is nothing but this is exactly what a supply chain attack could look like. Attacker trying to get their package installed when people make a common typing mistake. The package works exactly like the normal package and waits to gain users, and a year later it publishes a new version with a backdoor.\n\n\nI wish pypi (and other package indexes) did something about this like vaidating/verifying publishers and not auto installing unverified packages. Such a massive pain in almost all languages.\n\n[](https://pypi.org/project/django-handyhelpers/)"}
{"instruction": "Codebase Explorer (Turns Repos into Maps)", "input": "", "output": "Codebase Explorer (Turns Repos into Maps)\n**What My Project Does:**\n\nAst-visualizers core feature is taking a Python repo/codebase as input and displaying a number of interesting visuals derived from AST analysis. Here are the main features:\n\n* Abstract Syntax Trees of individual files with color highlighting\n* Radial view of a files AST (Helpful to get a quick overview of where big functions are located)\n* Complexity color coding, complex sections are highlighted in red within the AST.\n* Complexity chart, a line chart showing complexity per each line (eg line 10 has complexity of 5) for the whole file.\n* Dependency Graph shows how files are connected by drawing lines between files which import each other (helps in spotting circular dependencies)\n* Dashboard showing you all 3rd party libraries used and a maintainability score between 0-100 as well as the top 5 refactoring candidates.\n\nComplexity is defined as cyclomatic complexity according to McCabe. The Maintainability score is a combination of average file complexity and average file size (Lines of code).\n\n**Target Audience**:\n\nThe main people this would benefit are:\n\n* Devs onboarding large codebases (dependency graph is basically a map)\n* Students trying to understand ASTs in more detail (interactive tree renderings are a great learning tool)\n* Team Managers making sure technical debt stays minimal by keeping complexity low and paintability score high.\n* Vibe coders who could monitor how bad their spaghetti codebase really is / what areas are especially dangerous\n\n**Comparison:**\n\nThere are a lot of visual AST explorers, most of these focus on single files and classic tree style rendering of the data.\n\nAst-visualizer aims to also interpret this data and visualize it in new ways (radial, dependency graph etc.)\n\nProject Website: [ast-visualizer](https://ast-visualizer.com?utm_source=reddit_python)\n\nGithub: [Gitlab Repo](https://gitlab.com/swupel/ast-vsiualizer)"}
{"instruction": "[Project] fullbleed 0.1.12 — browserless HTML/CSS → PDF for Python (CLI + API, deterministic + JSON/", "input": "", "output": "[Project] fullbleed 0.1.12 — browserless HTML/CSS → PDF for Python (CLI + API, deterministic + JSON/\nHi r/Python,\n\nPosting as an individual contributor (not a marketing post). Looking for technical feedback.\n\n# What My Project Does\n\n`fullbleed` is a Rust PDF engine with Python bindings + a CLI. It converts **HTML/CSS → PDF** (optionally PNG page renders) **without running a browser**.\n\nAutomation/CI + tool/agent-friendly features:\n\n* machine-readable output: `--json`, `--json-only`, `--schema`\n* deterministic output: render hash + reproducibility record/check\n* optional PNG renders (useful for visual diffs/review loops)\n* debug artifacts (glyph coverage, page data, JIT/perf logs)\n\n# Component-style architecture (optional, not required)\n\nOne design path in the scaffold is component-driven Python that abstracts raw HTML construction in a familiar way. You can ignore this entirely and just pass your own HTML/CSS strings if you prefer.\n\nExample shape (multiple files):\n\n    # components/header.py\n    from dataclasses import dataclass\n    from .fb_ui import component, el\n    from .primitives import Stack, Text\n\n    (frozen=True)\n    class HeaderData:\n        title: str\n        subtitle: str\n\n    u/component\n    def Header(data: HeaderData):\n        return Stack(\n            Text(data.title, tag=\"h1\", class_name=\"header-title\"),\n            Text(data.subtitle, tag=\"p\", class_name=\"header-subtitle\"),\n            tag=\"header\",\n            class_name=\"doc-header\",\n        )\n\n    # report.py\n    import fullbleed\n    from components.fb_ui import render_component, el\n    from components.header import Header, HeaderData\n\n    def build_html():\n        root = el(\"main\", Header(HeaderData(\"Statement\", \"January 2026\")))\n        return render_component(root)\n\n    def render():\n        engine = fullbleed.PdfEngine(page_width=\"8.5in\", page_height=\"11in\", margin=\"0.5in\")\n        html = build_html()\n        css = \"...component css + report css...\"\n        engine.render_pdf_to_file(html, css, \"output/report.pdf\")\n\n\nWhy this approach (when using Python for HTML composition):\n\n* encourages reusable, testable document components\n* gives a “render-safe selector” contract via scaffolded primitives/components\n* keeps styling modular and predictable\n* still allows raw HTML/CSS whenever users want direct control\n\n# Target Audience\n\nPython developers building document pipelines such as:\n\n* invoices, statements, letters, reports\n* batch/templated PDF generation\n* CI workflows that need reproducibility + structured diagnostics\n* iterative HTML/CSS layout work where you want PDF + PNG from the same renderer (human or AI-assisted)\n\n# Comparison\n\n* **Browser-based HTML→PDF (Playwright/Puppeteer, etc.)**: great if you need JS runtime / full browser behavior. `fullbleed` is intentionally **browserless** and aims for **deterministic + inspectable** outputs.\n* **Other HTML→PDF tools**: many generate PDFs, but `fullbleed` is specifically focused on a strong CLI/JSON contract + reproducibility records + debug artifacts for pipelines.\n\n# Quick Example\n\n    pip install fullbleed\n    fullbleed render --html report.html --css report.css --out report.pdf --json\n    fullbleed render --html report.html --css report.css --out report.pdf --emit-image out_images\n\n\n# Status / Feedback Requested\n\nEarly but usable. I’d love feedback on:\n\n* Python API ergonomics\n* CLI/JSON contract quality (what would you change?)\n* component/scaffold approach for real production do"}
{"instruction": "What's Python cloud hosting using these days?", "input": "", "output": "What's Python cloud hosting using these days?\nHey, everyone!\n\nI'm trying to find a decent home for my side projects (FastAPI stuff, one Django app, and a Celery worker that scrapes data overnight). Nothing crazy, I just want to SSH in, set up a venv, point Gunicord at my WSGI app, and not have the provider babysit my stack. Pay-as-you-go is a big plus since some of my bots only run a few hours a day.\n\nSo far I've looked at DO, Vultr, Serverspace and Linode - each has its own quirks around pricing, regions, and how much hand-holding they do.\n\nWhat are you all running your Python apps on? Any hidden gem I'm missing, especially for heavier ML workloads or Celery queues?\n\nThanks!"}
{"instruction": "Jetbase - A Modern Python Database Migration Tool (Alembic alternative)", "input": "", "output": "Jetbase - A Modern Python Database Migration Tool (Alembic alternative)\nHey everyone! I built a database migration tool in Python called [Jetbase](https://github.com/jetbase-hq/jetbase).\n\nI was looking for something more Liquibase / Flyway style than Alembic when working with more complex apps and data pipelines but didn’t want to leave the Python ecosystem. So I built Jetbase as a Python-native alternative.\n\nSince Alembic is the main database migration tool in Python, here’s a quick comparison:\n\nJetbase has all the main stuff like upgrades, rollbacks, migration history, and dry runs, but also has a few other features that make it different.\n\n**Migration validation**\n\nJetbase validates that previously applied migration files haven’t been modified or removed before running new ones to prevent different environments from ending up with different schemas\n\nIf a migrated file is changed or deleted, Jetbase fails fast.\n\nIf you want Alembic-style flexibility you can disable validation via the config\n\n**SQL-first, not ORM-first**\n\nJetbase migrations are written in **plain SQL**.\n\nAlembic supports SQL too, but in practice it’s usually paired with SQLAlchemy. That didn’t match how we were actually working anymore since we switched to always use plain SQL:\n\n* Complex queries were more efficient and clearer in raw SQL\n* ORMs weren’t helpful for data pipelines (ex. S3 → Snowflake → Postgres)\n* We explored and validated SQL queries directly in tools like DBeaver and Snowflake and didn’t want to rewrite it into SQLAlchemy for our apps\n* Sometimes we queried other teams’ databases without wanting to add additional ORM models\n\n**Linear, easy-to-follow migrations**\n\nJetbase enforces **strictly ascending version numbers**:\n\n`1 → 2 → 3 → 4`\n\nEach migration file includes the version in the filename:\n\n`V1.5__create_users_table.sql`\n\nThis makes it easy to see the order at a glance rather than having random version strings. And jetbase has commands such as `jetbase history` and `jetbase status` to see applied versus pending migrations.\n\n**Linear migrations also leads to handling merge conflicts differently than Alembic**\n\nIn Alembic’s graph-based approach, if 2 developers create a new migration linked to the same down revision, it creates 2 heads. Alembic has to solve this merge conflict (flexible but makes things more complicated)\n\nJetbase keeps migrations fully linear and chronological. There’s always a single latest migration. If two migrations try to use the same version number, Jetbase fails immediately and forces you to resolve it before anything runs.\n\nThe end result is a migration history that stays predictable, simple, and easy to reason about, especially when working on a team or running migrations in CI or automation.\n\n**Migration Locking**\n\nJetbase has a lock to only allow one migration process to run at a time. It can be useful when you have multiple developers / agents / CI/CD processes running to stop potential migration errors or corruption.\n\nRepo: [https://github.com/jetbase-hq/jetbase](https://github.com/jetbase-hq/jetbase)\n\nDocs: [https://jetbase-hq.github.io/jetbase/](https://jetbase-hq.github.io/jetbase/)\n\n**Would love to hear your thoughts / get some feedback!**\n\nIt’s super easy to get started!\n\n`pip install jetbase`\n\n    # Initalize jetbase\n    jetbase init\n\n`cd jetbase`\n\n(Add your `sqlalchemy_url` to `jetbase/env.py`. Ex. sqlite:///[test.db](http://test.db))\n\n    # Generate new migration file: V1__create_users_table.sql:"}
{"instruction": "I tested structured output from 288 LLM calls and logged every way JSON breaks. Here's what I found", "input": "", "output": "I tested structured output from 288 LLM calls and logged every way JSON breaks. Here's what I found\nI've been building Python services that consume LLM output for the past few years, and I kept accumulating the same pile of regex fixups for broken JSON in every project. Markdown fences, trailing commas, Python booleans inside JSON, truncated objects, unescaped quotes, the usual.\n\nInstead of keeping a private junk drawer of string manipulations, I decided to actually study the problem. Ran structured output prompts through 288 model calls across every major provider and catalogued what breaks, how often, and whether the failure modes are consistent across model families. (Spoiler: they are. Weirdly consistent.)\n\nWrote it up here: [What Breaks When You Ask an LLM for JSON](https://thecrosswalk.news/what-breaks-when-you-ask-an-llm-for-json)\n\nThe article covers:\n\n- A taxonomy of the 8 most common structured output failures\n- Why the order you apply repairs in matters (this was the part that surprised me most)\n- Why JSON mode helps but doesn't solve the problem\n- What changes when you need to support YAML and TOML alongside JSON\n\nThe findings eventually turned into a library (outputguard), but the article stands on its own if you just want to understand the failure modes. Curious if other people are seeing the same patterns."}
{"instruction": "Network monitoring dashboard built with Flask, scapy, and nmap", "input": "", "output": "Network monitoring dashboard built with Flask, scapy, and nmap\nbuilt a home network monitor as a learning project useful to anyone.\n\nwhat it does: monitors local network in real time, tracks devices, bandwidth usage per device, and detects anomalies like new unknown devices or suspicious traffic patterns.\n\ntarget audience: educational/homelab project, not production ready. built for learning networking fundamentals and packet analysis. runs on any linux machine, good for raspberry pi setups.\n\ncomparison: most alternatives are either commercial closed source like fing or heavyweight enterprise tools like ntopng. this is intentionally simple and focused on learning. everything runs locally, no cloud, full control. anomaly detection is basic rule based so you can actually understand what triggers alerts, not black box ml.\n\ntech stack:\n\n* flask for web backend + api\n* scapy for packet sniffing / bandwidth monitoring\n* python-nmap for device discovery\n* sqlite for data persistence\n* chart.js for visualization\n\nwas a good way to learn about networking protocols, concurrent packet processing, and building a full stack monitoring application from scratch.\n\ncode + screenshots: [https://github.com/torchiachristian/HomeNetMonitor](https://github.com/torchiachristian/HomeNetMonitor)\n\nfeedback welcome, especially on the packet sniffing implementation and anomaly detection logic"}
{"instruction": "Teaching services online for kids/teenagers?", "input": "", "output": "Teaching services online for kids/teenagers?\nMy son (13) is interested in programming. I would like to sign him up for some introductory (and fun for teenagers) online program. Are there any that you’ve seen that you’d be able to recommend. Paid or unpaid are fine."}
{"instruction": "cf-taskpool: A concurrent.futures-style pool for async tasks", "input": "", "output": "cf-taskpool: A concurrent.futures-style pool for async tasks\nHey everyone! I've just released **[cf-taskpool](https://pypi.org/project/cf-taskpool/)**, a Python 3.11+ library that brings the familiar `ThreadPoolExecutor`/`ProcessPoolExecutor` API to asyncio coroutines. In fact it's not just the API: both the implementation and the tests are based on stdlib's `concurrent.futures`, avoiding garbage collection memory leaks and tricky edge cases that more naive implementations would run into.\n\nAlso, 100% organic, human-written code: no AI slop here, just good old-fashioned caffeine-fueled programming.\n\nWould love to hear your feedback!\n\n## What My Project Does\n\n`cf-taskpool` provides `TaskPoolExecutor`, which lets you execute async coroutines using a pool of asyncio tasks with controlled concurrency. It implements the same API you already know from `concurrent.futures`, but returns `asyncio.Future` objects that work seamlessly with `asyncio.wait()`, `asyncio.as_completed()`, and `asyncio.gather()`.\n\n**Quick example:**\n\n```python\nimport asyncio\nfrom cf_taskpool import TaskPoolExecutor\n\nasync def fetch_data(url: str) -> str:\n    await asyncio.sleep(0.1)\n    return f\"Data from {url}\"\n\nasync def main():\n    async with TaskPoolExecutor(max_workers=3) as executor:\n        future = await executor.submit(fetch_data, \"https://example.com\")\n        result = await future\n        print(result)\n\nasyncio.run(main())\n```\n\nIt also includes a `map()` method that returns an async iterator with optional buffering for memory-efficient processing of large iterables.\n\n## Target Audience\n\nThis library is for Python developers who:\n\n- Need to limit concurrency when running multiple async operations\n- Want a clean, familiar API instead of managing semaphores manually\n- Are already comfortable with `ThreadPoolExecutor`/`ProcessPoolExecutor` and want the same interface for async code\n- Need to integrate task pools with existing asyncio utilities like `wait()` and `as_completed()`\n\nIf you're working with async/await and need backpressure or concurrency control, this might be useful.\n\n## Comparison\n\n**vs. `asyncio.Semaphore` or `asyncio.Queue`:** These are great for simple cases where you create all tasks upfront and don't need backpressure. However, they require more manual orchestration. Chek out these links for context:\n- https://stackoverflow.com/questions/48483348/how-to-limit-concurrency-with-python-asyncio\n- https://death.andgravity.com/limit-concurrency\n\n**vs. existing task pool libraries:** There are a couple libraries that attempt to solve this (async-pool, async-pool-executor, asyncio-pool, asyncio-taskpool, asynctaskpool, etc.), but most are unmaintained and have ad-hoc APIs. `cf-taskpool` instead uses the standard `concurrent.futures` interface.\n\n## Links\n\n- [PyPI](https://pypi.org/project/cf-taskpool/)\n- [GitHub](https://github.com/gsakkis/cf-taskpool)"}
{"instruction": "Rethinking the IDE: Moving from text files to a graph-based IDE", "input": "", "output": "Rethinking the IDE: Moving from text files to a graph-based IDE\n# What My Project Does\n\nV‑NOC(Virtual Node Code) is a graph‑based IDE that sits on top of your existing files. Instead of treating code as a long list of text files, it treats the codebase like a map that you can navigate, zoom into, and filter based on what you are working on.\n\nThe source code stays exactly the same. The graph is an additional structural layer used only for understanding, navigation, debugging, and tooling.\n\nThe main idea is to reduce the mental effort required to understand large or unfamiliar codebases  for both humans and LLMs  by making structure explicit and persistent.\n\n# The Problem It Tries to Solve\n\nModern development is built almost entirely around files. Files are not real structures — they are flat text. They only make sense when a human or an LLM reads them and reconstructs the logic in their head.\n\nBecause of this, code, logs, and documentation are disorganized by default. There is no real connection being tracked between them.\n\nThis forces a bottom‑up way of working. To understand or change one small thing, you often need to understand many other parts first. You start from low‑level details and slowly work your way up, even when your goal is high‑level.\n\nIn practice, this means humans are doing a computer’s job. We repeatedly read files, trace function calls, and rebuild a mental model of the system in our heads. That model is fragile and temporary  it disappears when we switch tasks or move to another part of the codebase.\n\nAs the codebase grows, this problem grows much faster than the code itself. More files, more functions, and more connections create chaos. The number of relationships you need to remember increases rapidly, and the mental energy required to keep everything straight becomes overwhelming. Current file-based systems mix concerns and force you to load unrelated context just to understand one small change.\n\nInstead of spending energy on reasoning or design, developers spend it on remembering where things are and how they connect  work the computer could track automatically.\n\n# How V‑NOC Works (High Level)\n\n# Graph‑Based Structure\n\nV‑NOC builds a graph‑based structure on top of your existing files. The physical folder and file hierarchy is converted into a graph, using the existing structure as the top level so it still feels familiar.\n\nEvery file and folder is assigned a stable ID. Its identity stays the same even if it is renamed or moved. This allows notes, documentation, logs, and history to stay attached to the logic itself instead of breaking when paths change.\n\n# Deep Logic Extraction (Static and Dynamic Analysis)\n\nV‑NOC goes deeper than files. Using static analysis, every function and class is extracted and treated as a first‑class node in the graph.\n\nDynamic analysis is then used to understand how the code actually runs. By combining both, V‑NOC builds accurate call graphs and full call chains for each function.\n\nThis makes it possible to focus only on the functions involved in a specific flow. V‑NOC can slice those functions out of their original files and present them together in a single, focused view.\n\nOnly the functions that participate in the selected call chain are shown. Everything else — unrelated functions, files, and boilerplate  is temporarily hidden. Instead of manually tracing code and rebuilding a mental model, the structure is already there and reflects how the system works in the real world.\n\n# Seman"}
{"instruction": "Opticol: memory optimized python collections", "input": "", "output": "Opticol: memory optimized python collections\nHi everyone,\n\nI just created a new library called [opticol](https://github.com/lessico/opticol/) (which stands for optimized collections), which I wanted to share with the community. The idea of the library is to create space optimized versions of Sequence, Set, and Mapping for small collections leveraging the collections.ABC vocabulary.\n\n## What My Project Does\nCreates optimized versions of the main python collection types (Sequence, Set, Mapping) along with vocabulary types and convenience methods for transforming builtins to the optimized type.\n\nFor collections of size 3 or less, it is pretty trivial (using slots) to create an object that can act as a collection, but uses notably less memory than the builtins. Consider the fact that an empty set requires 216 bytes, or a dictionary with one element requires 224 bytes. Applications that create many (on the order of 100k to a million) of these objects can substantially reduce their memory usage with this library.\n\n## Target Audience\n\nThis will benefit users who use Python for various forms of data analysis. These problems often have many collection instances, which can often be just a few items. I myself have run into issues with memory pressure like this with some NLP datasets. Additionally, this is helpful for those doing this primarily in Python or for situations where dropping to a lower level language is not advantageous yet.\n\n## Comparison\n\nI could not find a similar library to this, nor even discussion of implementing such an idea. I would be happy to update this section if something comes up, but as far as I know, there are no direct comparisons.\n\nAnyway, it's currently a beta release as I'm working on finishing up the last unit tests, but the main use case generally works. I'm also very interested in any feedback on the project itself or other optimizations that may be good to add!"}
{"instruction": "graphqlite - Add graph database features to SQLite with Cypher queries", "input": "", "output": "graphqlite - Add graph database features to SQLite with Cypher queries\nI wanted to share a library I've been building. GraphQLite turns any SQLite database into a graph database that you can query with Cypher.\n\nThe API is straightforward—you create a Graph object pointed at a database file, add nodes and edges with properties, then query them using Cypher pattern matching. It also includes built-in graph algorithms like PageRank and Dijkstra if you need them.\n\nWhat I like about this approach is that everything stays in a single file. No server to manage, no configuration to fiddle with. If you're building something that needs relationship modeling but doesn't warrant a full graph database deployment, this might be useful.\n\nIt also pairs nicely with sqlite-vec if you're building GraphRAG pipelines—you can combine vector similarity search with graph traversals to expand context.\n\n\\`pip install graphqlite\\`\n\n\\*\\*What My Project Does\\*\\* -  its an sqlite extension that provides the cypher query language, installable and usable as a python library.\n\n\\*\\*Target Audience\\*\\* - anyone wanting to do work with relational data at smaller scales, learning about knowledge graphs and wishing to avoid dealing with external services.\n\n\\*\\*Comparison\\*\\*  - Neo4j - but no servers needed.\n\nGitHub: [https://github.com/colliery-io/graphqlite](https://github.com/colliery-io/graphqlite)"}
{"instruction": "Robyn(web framework) introduces @app.websocket decorator syntax", "input": "", "output": "Robyn(web framework) introduces @app.websocket decorator syntax\nFor the unaware - [Robyn](https://github.com/sparckles/Robyn) is a fast, async Python web framework built on a Rust runtime.\n\nWe're introducing a new `@app.websocket` decorator syntax for WebSocket handlers. It's a much cleaner DX compared to the older class-based approach, and we'll be deprecating the old syntax soon.\n\nThis is also groundwork for upcoming Pydantic integration.\n\nWanted to share it with folks outside the Robyn Discord.\n\nYou can check out the release at - [https://github.com/sparckles/Robyn/releases/tag/v0.78.0](https://github.com/sparckles/Robyn/releases/tag/v0.78.0)\n\nLet me know if you have any questions/suggestions :D"}
{"instruction": "The Rise of the Command Line: building a new IDE (2017–2026)", "input": "", "output": "The Rise of the Command Line: building a new IDE (2017–2026)\nAuthor here. This is a nine-year account of building Rune, a new IDE (1.1 added support for Python). It started when my Vim's go-to-definition broke in 2017 and I decided to build my own editor rather than adopt an IDE: [https://rune.build/blog/the-rise-of-the-command-line](https://rune.build/blog/the-rise-of-the-command-line)"}
{"instruction": "I scanned 17,316 malicious packages and here's what actually works", "input": "", "output": "I scanned 17,316 malicious packages and here's what actually works\n**What It Does:**\nStatic analysis tool that scans npm and PyPI packages for supply chain attacks before they hit your CI/CD pipeline. Detects shell injection, credential theft, obfuscation, and malicious install hooks using pattern matching + AST analysis.\n\n**Target Audience:**\nProduction use for teams running CI/CD pipelines. Research prototype but functional - I've been using it for a few weeks to catch suspicious packages before merge.\n\n**Comparison:**\n- **vs Snyk/Socket:** Those are commercial SaaS ($$$). This is free, MIT licensed, runs locally in your CI.\n- **vs pip-audit/Safety:** They only catch known CVEs. This catches zero-day typosquatting and novel malware patterns.\n- **vs Bandit:** Bandit scans your own code. This scans third-party packages you're about to install.\n\n---\n\nDownloaded every package from the QUT-DV25 malware dataset (14,272 PyPI + 15,059 npm samples) and ran them through the analyzer I built.\n\nResults:\n- 89.6% of npm malware: detectable with regex\n- 82.2% of PyPI malware: detectable with regex\n\nThe most common patterns:\n1. Shell injection in postinstall hooks (npm) - 34% of samples\n2. `setup.py` with `exec()` calls (PyPI) - 28% of samples\n3. Obfuscated code (Buffer.from base64) - 19% of samples\n4. Environment variable exfiltration - 15% of samples\n\nWhat actually evades detection:\n- Multi-stage deobfuscation\n- Time-delayed payloads\n- Geofencing (only runs in certain countries)\n- VM detection (only runs if not in sandbox)\n\nThe surprising part? Most attackers don't bother with evasion. They're banking on people not checking.\n\nBuilt a scanner for CI/CD that blocks the obvious stuff: https://github.com/Otsmane-Ahmed/ci-supplychain-guard\n\nIf you're running PyPI packages in production, might want to scan them first."}
{"instruction": "pydantic-pick: Dynamically extract subset Pydantic V2 models while preserving validators and methods", "input": "", "output": "pydantic-pick: Dynamically extract subset Pydantic V2 models while preserving validators and methods\nHello everyone,\n\nI wanted to share a library I recently built called `pydantic-pick`.\n\n**What My Project Does**\n\nWhen working with FastAPI or managing prompt history of language models , I often end up with large Pydantic models containing heavy internal data like password hashes, database metadata, large strings or tool\\_responses. Creating thinner versions of these models for JSON responses or token optimization usually means manually writing and maintaining multiple duplicate classes.\n\n`pydantic-pick` is a library that recursively rebuilds Pydantic V2 models using dot-notation paths while safely carrying over your @`field_validator` functions, @`computed_field` properties, `Field` constraints, and user-defined methods.\n\nThe main technical challenge was handling methods that rely on data fields the user decides to omit. If a method tries to access `self.password_hash` but that field was excluded from the subset, the application would crash at runtime. To solve this, the library uses Python's `ast` module to parse the source code of your methods and computed fields during the extraction process. It maps exactly which `self.attributes` are accessed. If a method relies on a field that you omitted, the library safely drops that method from the new model as well.\n\n**Usage Example**\n\nHere is a quick example of deep extraction and AST omission:\n\n    from pydantic import BaseModel\n    from pydantic_pick import create_subset\n\n    class Profile(BaseModel):\n        avatar_url: str\n        billing_secret: str\n    # We want to drop this\n\n    class DBUser(BaseModel):\n        id: int\n        username: str\n        password_hash: str\n    # And drop this\n        profiles: list[Profile]\n\n        def check_password(self, guess: str) -> bool:\n\n    # This method relies on password_hash\n            return self.password_hash == guess\n\n    # Create a subset using dot-notation to drill into nested lists\n    PublicUser = create_subset(\n        DBUser,\n        (\"id\", \"username\", \"profiles.avatar_url\"),\n        \"PublicUser\"\n    )\n\n    user = PublicUser(id=1, username=\"alice\", profiles=[{\"avatar_url\": \"img.png\"}])\n\n    # Because password_hash was omitted, AST parsing automatically drops check_password\n    # Calling user.check_password(\"secret\") will raise a custom AttributeError\n    # explaining it was intentionally omitted during extraction.\n\n\nTo prevent performance issues in API endpoints, the generated models are cached using `functools.lru_cache`, so subsequent calls for the same subset return instantly from memory.\n\n**Target Audience**\n\nThis tool is intended for backend developers working with FastAPI or system architects building autonomous agent frameworks who need strict type safety and validation on dynamic data subsets. It requires Python 3.10 or higher and is built specifically for Pydantic V2.\n\n**Comparison**\n\nThe ability to create subset models (similar to TypeScript's `Pick` and `Omit`) is a highly requested feature in the Pydantic community (e.g., Pydantic GitHub issues #5293 and #9573). Because Pydantic does not support this natively, developers currently rely on a few different workarounds:\n\n* **BaseModel.model\\_dump(include={...}):** Standard Pydantic allows you to omit fields during serialization. However, this only filters the output dictionary at runtime. It does not provide a true Python class th"}
{"instruction": "Single file Python CLIs when do you split, when do you keep it monolithic?", "input": "", "output": "Single file Python CLIs when do you split, when do you keep it monolithic?\nWorking on a tool that's grown to \\~4000 LOC in one .py file. argparse + 18 subcommands, stdlib + pyyaml only. Tests are in a separate dir.\n\nSingle-file has been great for:\n\n\\- Debugging (one file to grep)\n\n\\- Distribution (one wheel, no package layout decisions)\n\n\\- Onboarding contributors\n\nBut I'm starting to wonder if it's worth keeping monolithic at this size. What's your threshold for splitting? Is it LOC, or coupling, or \"I can't navigate it anymore\"?"}
{"instruction": "Stanford CS 25 Transformers Course (OPEN TO ALL | Starts Tomorrow)", "input": "", "output": "Stanford CS 25 Transformers Course (OPEN TO ALL | Starts Tomorrow)\n**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](https://web.stanford.edu/class/cs25/recordings/)**. Course website:** [**https://web.stanford.edu/class/cs25/**](https://web.stanford.edu/class/cs25/)**.**\n\nInterested 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!\n\nEach 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!\n\nCS25 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.\n\nOur class has a global audience, and millions of total views on [YouTube](https://www.youtube.com/playlist?list=PLoROMvodv4rNiJRchCzutFw5ItR_Z27CM). Our class with Andrej Karpathy was the second most popular [YouTube video](https://www.youtube.com/watch?v=XfpMkf4rD6E&ab_channel=StanfordOnline) uploaded by Stanford in 2023!\n\nLivestreaming and auditing (in-person or [Zoom](https://stanford.zoom.us/j/[PHONE]?pwd=Z2hX1bsP2HvjolPX4r23mbHOof5Y9f.1)) are available to all! And join our 6000+ member Discord server (link on website).\n\nThanks to Modal, AGI House, and MongoDB for sponsoring this iteration of the course."}
{"instruction": "Give me the best package manager setup. I am old and crusty.", "input": "", "output": "Give me the best package manager setup. I am old and crusty.\nI know this is probably the 100s post about this topic, but I would appreciate, if someone can give me some input about package managers. So far I have used either venv/pip directly or conda for my needs of separation and installation of packages. Now I am using a controversial yet popular archlinux dotfile script installer distro that has mise-en-place enabled by default in my shell and I have realized that my knowledge about these kinda of tools is almost 10 years old, when I first seriously touched python in Uni.\n\nI need a package manager that can do everything that conda/pip can do, and does what I want it to do, when I say so explicitly. I especially need CUDA for Jax and Torch and Tensorflow packages. Sure, these are not (pure) python packages, but I expect it to be \"just handled\". All of it, including the Nvidia stuff. I have spend to much time fucking up linux distros using nvidias install script, while the current pip install \"jax\\[cudaxx\\]\" just works. I don't know how, for all I care it could be machine elves, as long as I don't have to touch any cuda packages manually again.\n\nShould I invest the time to try something new (mise, uv), or is it not the standard yet? The big ML suites still all recommend pip."}
{"instruction": "Python modules: retry framework, OpenSSH client w/ fast conn pooling, and parallel task-tree schedul", "input": "", "output": "Python modules: retry framework, OpenSSH client w/ fast conn pooling, and parallel task-tree schedul\nI’m the author of `bzfs`, a Python CLI for ZFS snapshot replication across fleets of machines ([https://github.com/whoschek/bzfs](https://github.com/whoschek/bzfs)).\n\nBuilding a replication engine forces you to get a few things right: retries must be disciplined (no \"accidental retry\"), remote command execution must be fast, predictable and scalable, and parallelism must respect hierarchical dependencies.\n\nThe modules below are the pieces I ended up extracting; they’re Apache-2.0, have zero dependencies, and installed via `pip install bzfs` (Python `>=3.9`).\n\nWhere these fit well:\n\n* Wrapping flaky operations with *explicit*, policy-driven retries (subprocess calls, API calls, distributed systems glue)\n* Running lots of SSH commands with low startup latency (OpenSSH multiplexing + safe pooling)\n* Processing hierarchical resources in parallel without breaking parent/child ordering constraints\n\nModules:\n\n* `bzfs_main.util.retry` — retries are opt-in via `RetryableError` (prevents accidental retries), jittered exponential backoff w/ cap, elapsed-time budgets, cancellation + hooks [https://github.com/whoschek/bzfs/blob/main/bzfs\\_main/util/retry.py](https://github.com/whoschek/bzfs/blob/main/bzfs_main/util/retry.py)\n* `bzfs_main.util.connection` — thread-safe SSH command runner + connection pool using OpenSSH multiplexing (ControlMaster/ControlPersist); with `connection_lease` for safe low latency connection reuse across processes [https://github.com/whoschek/bzfs/blob/main/bzfs\\_main/util/connection.py](https://github.com/whoschek/bzfs/blob/main/bzfs_main/util/connection.py) [https://github.com/whoschek/bzfs/blob/main/bzfs\\_main/util/connection\\_lease.py](https://github.com/whoschek/bzfs/blob/main/bzfs_main/util/connection_lease.py)\n* `bzfs_main.util.parallel_tasktree` — dependency-aware scheduler for hierarchical workloads (ancestors finish before descendants start), customizable completion callbacks [https://github.com/whoschek/bzfs/blob/main/bzfs\\_main/util/parallel\\_tasktree.py](https://github.com/whoschek/bzfs/blob/main/bzfs_main/util/parallel_tasktree.py)\n\nExample (SSH + retries, self-contained):\n\n    import logging\n    from subprocess import DEVNULL, PIPE\n\n    from bzfs_main.util.connection import (\n        ConnectionPool,\n        create_simple_minijob,\n        create_simple_miniremote,\n    )\n    from bzfs_main.util.retry import Retry, RetryPolicy, RetryableError, call_with_retries\n\n    log = logging.getLogger(__name__)\n    remote = create_simple_miniremote(log=log, ssh_user_host=\"alice@[IP]\")\n    pool = ConnectionPool(remote, connpool_name=\"example\")\n    job = create_simple_minijob()\n\n\n    def run_cmd(retry: Retry) -> str:\n        try:\n            with pool.connection() as conn:\n                return conn.run_ssh_command(\n                    cmd=[\"echo\", \"hello\"],\n                    job=job,\n                    check=True,\n                    stdin=DEVNULL,\n                    stdout=PIPE,\n                    stderr=PIPE,\n                    text=True,\n                ).stdout\n        except Exception as exc:\n            raise RetryableError(display_msg=\"ssh\") from exc\n\n\n    retry_policy = RetryPolicy(\n        max_retries=5,\n        min_sleep_secs=0,\n        initial_max_sleep_secs=0.1,\n        max_sleep_secs=2,\n        max_elapsed_secs=30,\n    )\n    print(call_with_retries(run_cmd, policy=retry_policy,"}
{"instruction": "Third party Python libraries and supply chain security", "input": "", "output": "Third party Python libraries and supply chain security\nHow are people handling security around third party Python libraries without making development a pain?\n\nThird party Python packages are obviously useful but every dependency can also become a supply chain risk. Private package repositories, dependency scanning and stricter review policies all help but they can add friction fast.\n\nAre teams mostly trusting public registries with additional controls or using curated libraries? Curious what actually works when you have a lot of Python services."}
{"instruction": "pyochain - Rust-like Iterator, Result and Option in Python- Release [IP]", "input": "", "output": "pyochain - Rust-like Iterator, Result and Option in Python- Release [IP]\nHello everyone,\n\n3 months ago I shared my library pyochain:\n[https://www.reddit.com/r/Python/comments/1oe4n7h/pyochain\\_method\\_chaining\\_on\\_iterators\\_and/](https://www.reddit.com/r/Python/comments/1oe4n7h/pyochain_method_chaining_on_iterators_and/)\n\nSince then I've made a lot of progress, with new functionalities, better user API, performance improvements, and a more complete documentation.\n\nSo much progress in fact that I feel it's a good time to share it again.\n\n**Installation**\n\n`uv add pyochain`\n\n**Links**\n\n* **Source Code:** [https://github.com/OutSquareCapital/pyochain](https://github.com/OutSquareCapital/pyochain)\n* **Documentation:** [https://outsquarecapital.github.io/pyochain/](https://outsquarecapital.github.io/pyochain/)\n* **Pypi**: [https://pypi.org/project/pyochain/](https://pypi.org/project/pyochain/)\n\n# What My Project Does\n\nProvides:\n\n1. method chaining for Iterators and various collections types (Set, SetMut, Seq, Vec, Dict), with an API mirroring Rust whenever possible/pertinent\n2. Option and Result types\n3. Mixins classes for custom user extension.\n\nExamples below from the README of the project:\n\n    import pyochain as pc\n\n    res: pc.Seq[tuple[int, str]] = (\n        pc.Iter.from_count(1)\n        .filter(lambda x: x % 2 != 0)\n        .map(lambda x: x**2)\n        .take(5)\n        .enumerate()\n        .map_star(lambda idx, value: (idx, str(value)))\n        .collect()\n    )\n    res\n    # Seq((0, '1'), (1, '9'), (2, '25'), (3, '49'), (4, '81'))\n\nFor comparison, the above can be written in pure Python as the following (note that Pylance strict will complain because `itertools.starmap` has not the same overload exhaustiveness as pyochain's `Iter.map_star`):\n\n    import itertools\n\n    res: tuple[tuple[int, str], ...] = tuple(\n        itertools.islice(\n            itertools.starmap(\n                lambda idx, val: (idx, str(val)),\n                enumerate(\n                    map(lambda x: x**2, filter(lambda x: x % 2 != 0, itertools.count(1)))\n                ),\n            ),\n            5,\n        )\n    )\n    # ((0, '1'), (1, '9'), (2, '25'), (3, '49'), (4, '81'))\n\nThis could also be written with for loops, but would be even more unreadable, unless you quadruple the number of code lines.\n\nYes you could assign intermediate variables, but this is annoying, less autocomplete friendly, and more error prone.\n\nExample for Result and Option:\n\n    import pyochain as pc\n\n\n    def divide(a: int, b: int) -> pc.Option[float]:\n        return pc.NONE if b == 0 else pc.Some(a / b)\n\n\n    divide(10, 2)\n    # Some(5.0)\n    divide(10, 0).unwrap_or(-1.0)  # Provide a default value\n    # -1.0\n    # Convert between Collections -> Option -> Result\n    data = pc.Seq([1, 2, 3])\n    data.then_some()  # Convert Seq to Option\n    # Some(Seq(1, 2, 3))\n    data.then_some().map(lambda x: x.sum()).ok_or(\"No values\")  # Convert Option to Result\n    # Ok(6)\n    pc.Seq[int](()).then_some().map(lambda x: x.sum()).ok_or(\"No values\")\n    # Err('No values')\n    pc.Seq[int](()).then_some().map(lambda x: x.sum()).ok_or(\"No values\").ok()\n    # NONE\n\n# Target Audience\n\nThis library is aimed at Python developers who enjoy:\n\\- method chaining/functional style\n\\- None handling via Option types\n\\- explicit error returns types via Result\n\\- itertools/cytoolz/toolz/more-itertools functionnalities\n\nIt is fully tested (each method and each documentation exa"}
{"instruction": "I tested Python 3.13t free-threading — the CPU-bound speedup surprised me", "input": "", "output": "I tested Python 3.13t free-threading — the CPU-bound speedup surprised me\nI wrote a [practical article](https://code2trade.dev/free-threaded-python-3-13/) about Python 3.13t / free-threaded CPython.\n\nThe old rule was basically:\n\nCPU-bound task + Python threads = probably pointless\nCPU-bound task + multiprocessing = usually the answer\n\nThat rule is starting to change.\n\nPython 3.13 introduced an experimental free-threaded build where the GIL can be disabled, allowing Python threads to run concurrently across CPU cores.\n\nThe article covers:\n\n* Why the GIL existed;\n* Why removing it was historically difficult;\n* Reference counting and the single-thread performance problem;\n* Why earlier free-threading attempts were not accepted;\n* What changed with biased reference counting;\n* How to check whether the GIL is actually disabled;\n* ThreadPoolExecutor examples;\n* Benchmarking standard 3.13 vs 3.13t;\n* When multiprocessing is still the better choice.\n\nMy benchmark result on an i9-14900HX:\n\nStandard Python 3.13: 1.4798 seconds;\nPython 3.13t: 0.1841 seconds.\n\nObviously, benchmark numbers depend heavily on workload, CPU, Python build, and dependencies. But the relative difference on CPU-bound threaded code is hard to ignore.\n\nThe main caveat: this is not “free speed.”\n\nWithout the GIL, thread safety becomes your responsibility. Shared mutable state needs proper locking, and some C extensions may still re-enable the GIL or behave differently depending on support.\n\nI’m curious what people here think:\n\nIs free-threaded Python likely to change how you design CPU-bound Python applications, or will multiprocessing remain your default for a while?"}
{"instruction": "How to make flask able to handle large number of io requests?", "input": "", "output": "How to make flask able to handle large number of io requests?\nHey guys, what might be the best way to make flask handle large number of requests which simple wait and do nothing useful. Example say fetching data from an external api or proxying. Rn I am using gunicorn. With 10 workers and 5 threads. So that's about 50 requests at a time. But say I got 50 reqs and they are all waiting on something, the new reqs would wait in queue.\n\nWhat's the solution here to make it more like nodejs (or fastapi) which from what I hear can handle 1000s of such requests in a single worker. I have an existing codebase and I am unsure I wanna migrate it to fastapi. I also have a nextjs frontend. And I could delegate such tasks to nextjs but seems like splitting logic between 2 backends is kinda bad. Plus I like python and would wanna keep most of the stuff in python.\n\nI have plenty of ram and could just increase to more threads say 50 per worker. From what I read the options available are gevent and WsgiToAsgi but unsure how plug and play they are. And if they have any mess associated with them since they are plugins forcing flask to act like async.\n\nFor now I think adding more threads will suffice. But historically had some issues. Let me know if you have any experience or any solution on what might be best way possible."}
{"instruction": "Celery on AWS ECS - prevent lost tasks and ensure the work is always done", "input": "", "output": "Celery on AWS ECS - prevent lost tasks and ensure the work is always done\nRunning Celery on AWS ECS can be trickier than it seems if you want to avoid lost tasks and ensure all work is completed. Especially if you're frequently deploying to production and using autoscaling.\n\nThere are two main components for reliable processing:\n- Celery configuration updates\n- Structuring tasks\n\nFor Celery, you should update the following settings:\n- task_acks_late -> True: To treat tasks as successfully processed only after processing. Otherwise, tasks are not retried.\n- task_reject_on_worker_lost -> True: To ensure tasks are retried if workers die for any reason (e.g., warm shutdown + SIGKILL).\n- worker_prefetch_multiplier -> 1: To avoid unnecessarily delayed tasks.\n- broker_connection_retry_on_startup -> True: To make startups more reliable.\n- broker_transport_options -> {\"confirm_publish\": True}: To avoid unsubmitted tasks due to message transport issues.\n- Make sure exponential retries are enabled. This way, you ensure that tasks are retried in the event of an interruption.\n\nFor structuring tasks, use the following two approaches:\n- Batching: Instead of doing all the work at once, you split the work into batches. e.g., Process 1000 users, then submit the next job to process the next 1000 users.\n- Fan out: You can split the work between a \"scheduler\" task and \"execution\" tasks. e.g., One task to list all the users and submit email sending tasks, another task to actually send an email for the selected user\n\nThe same applies to other similar services, such as Heroku and Azure App Containers, which use short grace periods during rolling deployments and downscaling.\n\nYou can read a more elaborate tutorial here: https://jangiacomelli.com/blog/celery-on-aws-ecs/"}
{"instruction": "Better Python tests with inline-snapshot", "input": "", "output": "Better Python tests with inline-snapshot\nI've written [a blog post](https://pydantic.dev/articles/inline-snapshot) about one of my favourite libraries: `inline-snapshot`. Some key points within:\n\n- Why you should use the library: it makes it quick and easy to write rigorous tests that automatically update themselves\n- Why you should combine it with the `dirty-equals` library to handle dynamic values like timestamps and UUIDs\n- Why you should convert custom classes to plain dicts before snapshotting\n\nDisclaimer: I wrote this blog post for my company (Pydantic), but we didn't write the library, we just use it a lot and sponsor it. I genuinely love it and wanted to share to help support the author."}
{"instruction": "ZooCache – Distributed semantic cache for Python with smart invalidation (Rust core)", "input": "", "output": "ZooCache – Distributed semantic cache for Python with smart invalidation (Rust core)\nHi everyone,\n\nI’m sharing an open-source Python library I’ve been working on called **ZooCache**, focused on semantic caching for distributed systems.\n\n# What My Project Does\n\nZooCache provides a semantic caching layer with smarter invalidation strategies than traditional TTL-based caches.\n\nInstead of relying only on expiration times, it allows:\n\n* Prefix-based invalidation (e.g. invalidating `user:1` clears all related keys like `user:1:settings`)\n* Dependency-based cache entries\n* Protection against backend overload using the SingleFlight pattern\n* Distributed consistency using Hybrid Logical Clocks (HLC)\n\nThe core is implemented in Rust for performance, with Python bindings for easy integration.\n\n# Target Audience\n\nZooCache is intended for:\n\n* Backend developers working with Python services under high load\n* Distributed systems where cache invalidation becomes complex\n* Production environments that need stronger consistency guarantees\n\nIt’s not meant to replace simple TTL caches like Redis directly, but to complement them in scenarios with complex relationships between cached data.\n\n# Comparison\n\nCompared to traditional caches like Redis or Memcached:\n\n* TTL-based caches rely mostly on time expiration, while ZooCache focuses on semantic invalidation\n* ZooCache supports prefix and dependency-based invalidation out of the box\n* It prevents cache stampedes using SingleFlight\n* It handles multi-node consistency using logical clocks\n\nIt can still use Redis as an invalidation bus, but nodes may keep local high-performance storage (e.g. LMDB).\n\n**Repository:** [https://github.com/albertobadia/zoocache](https://github.com/albertobadia/zoocache)\n**Documentation:** [https://zoocache.readthedocs.io/en/latest/](https://zoocache.readthedocs.io/en/latest/)\n\n# Example Usage\n\n    from zoocache import cacheable, add_deps, invalidate\n\n    @cacheable\n    def generate_report(project_id, client_id):\n        add_deps([f\"client:{client_id}\", f\"project:{project_id}\"])\n        return db.full_query(project_id)\n\n    def update_project(project_id, data):\n        db.update_project(project_id, data)\n        invalidate(f\"project:{project_id}\")\n\n    def update_client_settings(client_id, settings):\n        db.update_client_settings(client_id, settings)\n        invalidate(f\"client:{client_id}\")\n\n    def delete_client(client_id):\n        db.delete_client(client_id)\n        invalidate(f\"client:{client_id}\")"}
{"instruction": "Can a CNN solve algorithmic tasks? My experiment with a Deep Maze Solver", "input": "", "output": "Can a CNN solve algorithmic tasks? My experiment with a Deep Maze Solver\n**TL;DR:** I trained a U-Net on 500k mazes. It’s great at solving small/medium mazes, but hits a limit on complex ones.\n\nHi everyone,\n\nI’ve always been fascinated by the idea of neural networks solving tasks that are typically reserved for deterministic algorithms. I recently experimented with training a **U-Net** to solve mazes, and I wanted to share the process and results.\n\n**The Setup:** Instead of using traditional pathfinding (like A\\* or DFS) at runtime, I treated the maze as an image segmentation problem. The goal was to input a raw maze image and have the model output a pixel-mask of the correct path from start to finish.\n\n**Key Highlights:**\n\n* **Infinite Data:** Since maze generation is deterministic, I used Recursive Division to generate mazes and DFS to solve them, creating a massive synthetic dataset of 500k+ pairs.\n* **Architecture:** Used a standard U-Net implemented in PyTorch.\n* **The \"Wall\":** The model is incredibly accurate on mazes up to 64x64, but starts to struggle with \"global\" logic on 127x127 scales, a classic challenge for CNNs without global attention.\n\nI wrote a detailed breakdown of the training process, the hyperparameters, and the loss curves here: [https://dineshgdk.substack.com/p/deep-maze-solver](https://dineshgdk.substack.com/p/deep-maze-solver)\n\nThe code is also open-sourced if you want to play with the data generator: [https://github.com/dinesh-GDK/deep-maze-solver](https://github.com/dinesh-GDK/deep-maze-solver)\n\nI'd love to hear your thoughts on scaling this, do you think adding Attention gates or moving to a Transformer-based architecture would help the model \"see\" the longer paths better?"}
{"instruction": "Saturday Showcase: What are you building with Python? 🐍", "input": "", "output": "Saturday Showcase: What are you building with Python? 🐍\nWhether it's a web app on Django/FastAPI, a data tool, or a complex automation script you finally got working; drop the repo or link below."}
{"instruction": "I wrote a book! \"Ultimate ONNX for Deep Learning Optimization\" (Edge ML)", "input": "", "output": "I wrote a book! \"Ultimate ONNX for Deep Learning Optimization\" (Edge ML)\nHey everyone,\n\nI’m excited to share that I’ve just published a new book titled **\"Ultimate ONNX for Deep Learning Optimization\"**.\n\nAs many of you know, taking a model from a research notebook to a production environment—especially on resource-constrained edge devices—is a massive challenge. ONNX (Open Neural Network Exchange) has become the de-facto standard for this, but finding a structured, end-to-end guide that covers the entire ecosystem (not just the \"hello world\" export) can be tough.\n\nI wrote this book to bridge that gap. It’s designed for ML Engineers and Embedded Developers who need to optimize models for speed and efficiency without losing significant accuracy.\n\n**What’s inside the book?** It covers the full workflow from export to deployment:\n\n* **Foundations:** Deep dive into ONNX graphs, operators, and integrating with PyTorch/TensorFlow/Scikit-Learn.\n* **Optimization:** Practical guides on Quantization, Pruning, and Knowledge Distillation.\n* **Tools:** Using ONNX Runtime and ONNX Simplifier effectively.\n* **Real-World Case Studies:** We go through end-to-end execution of modern models including **YOLOv12** (Object Detection), **Whisper** (Speech Recognition), and **SmolLM** (Compact Language Models).\n* **Edge Deployment:** How to actually get these running efficiently on hardware like the Raspberry Pi.\n* **Advanced:** Building custom operators and security best practices.\n\n**Who is this for?** If you are a Data Scientist, AI Engineer, or Embedded Developer looking to move models from \"it works on my GPU\" to \"it works on the device,\" this is for you.\n\n**Where to find it:** You can check it out on Amazon here:[https://www.amazon.in/dp/[PHONE]](https://www.amazon.in/dp/[PHONE])\n\nI’ve poured a lot of experience regarding the pain points of deployment into this. I’d love to hear your thoughts or answer any questions you have about ONNX workflows or the book content!\n\nThanks!"}
{"instruction": "Mitigating \"architectural drift\" in large Python backend codebases using AI tools", "input": "", "output": "Mitigating \"architectural drift\" in large Python backend codebases using AI tools\nI've been experimenting with AI agents and autocomplete platforms for a greenfield FastAPI project. In the first few weeks, it felt incredibly fast. But now that we've scaled to multiple routers, complex Pydantic schemas, and SQLAlchemy models, the structural debt is piling up.\n\nThe AI writes code that functions, but it constantly violates our architecture. It'll put complex business logic inside a route handler instead of the service layer, or it'll mess up async database sessions across modules. I find myself spending more time refactoring the structure of what it built than it would have taken to write the logic myself.\n\nIs anyone else hitting this scaling wall where AI utility drops off as codebase complexity grows? How are you keeping your system architecture clean?"}
{"instruction": "Is openpyxl still relevant?", "input": "", "output": "Is openpyxl still relevant?\nI'm a college student, I've just learned pandas and I was planning to start freelancing with openpyxl, pandas and numpy. Wanted to try gigs like data cleaning or automation services. But as I searched about openpyxl, I read that it's used to work with 2010 excel sheets. And that's all.\n\nSo my question was is this module/library still relevant?"}
{"instruction": "Update: copier-astral now uses prek (faster pre-commit) + bug fixes from your feedback", "input": "", "output": "Update: copier-astral now uses prek (faster pre-commit) + bug fixes from your feedback\nTwo weeks ago I shared copier-astral here and the response was incredible — thank you! The feedback helped me find and fix real bugs.\n\n**What's new since last post:**\n\n* Fixed `github_username` not being set during installation\n* Fixed `uv tool inject` bug\n* Fixed missing `ty` dependency in generated projects (#7)\n* Replaced `pre-commit` with `prek` — a faster Rust-based alternative (#17)\n* Added `pysentry-rs` and `semgrep` to scan for potential vulnerabilities\n* Now at 100+ stars\n\n**Quick reminder — what it does:**\n\nScaffolds a production-ready Python project with Astral's toolchain (uv, ruff, ty) + pytest, MkDocs, GitHub Actions, Docker. One command:\n\n    copier copy --trust gh:ritwiktiwari/copier-astral my-project\n\n**Looking for contributors:**\n\n3 open issues if anyone wants to help out: [https://github.com/ritwiktiwari/copier-astral/issues](https://github.com/ritwiktiwari/copier-astral/issues)\n\nThanks again — happy to answer any questions!\n\n**Links:**\n\n* GitHub: [https://github.com/ritwiktiwari/copier-astral](https://github.com/ritwiktiwari/copier-astral)\n* Docs: [https://ritwiktiwari.github.io/copier-astral/](https://ritwiktiwari.github.io/copier-astral/)"}
{"instruction": "Python Asyncio Crash Course: Complete Tutorial", "input": "", "output": "Python Asyncio Crash Course: Complete Tutorial\nI just published my first crash course on YouTube.\n\n\nIt starts by introducing async in general and why everybody is obsessed with it.\n\n\nLink: [https://www.youtube.com/watch?v=vve5SHVE\\_F0](https://www.youtube.com/watch?v=vve5SHVE_F0)\n\n\nThen, we compare other alternatives that you can use as well to speed up your program: asyncio vs threads vs multiprocessing.\n\n\nAfter that, we dive deeper into the Python way of implementing async by tackling coroutines, tasks, future low-level types, and how the event loop is used to schedule tasks concurrently.\n\n\n\nPlease like the video, and drop a comment on YouTube if the video is helpful."}
{"instruction": "Python tool that analyzes your system's hardware and determines which AI models you can run locally.", "input": "", "output": "Python tool that analyzes your system's hardware and determines which AI models you can run locally.\nGitHub: [https://github.com/Ssenseii/ariana](https://github.com/Ssenseii/ariana)\n\n**What My Project Does**\n\nAI Model Capability Analyzer is a Python tool that inspects your system’s hardware and tells you **which AI models you can realistically run locally**.\n\nIt automatically:\n\n* Detects CPU, RAM, GPU(s), and available disk space\n* Fetches metadata for **200+ AI models** (from Ollama and related sources)\n* Compares your system resources against each model’s requirements\n* Generates a **detailed compatibility report** with recommendations\n\nThe goal is to remove the guesswork around questions like *“Can my machine run this model?”* or *“Which models should I try first?”*\n\nAfter running the tool, you get a report showing:\n\n* How many models your system supports\n* Which ones are a good fit\n* Suggested optimizations (quantization, GPU usage, etc.)\n\n**Target Audience**\n\nThis project is primarily for:\n\n* Developers experimenting with **local LLMs**\n* People new to running AI models on consumer hardware\n* Anyone deciding **which models are worth downloading** before wasting bandwidth and disk space\n\nIt’s **not meant for production scheduling or benchmarking**. Think of it as a practical analysis and learning tool rather than a deployment solution.\n\n**Comparison**\n\nCompared to existing alternatives:\n\n* **Ollama** tells you *how* to run models, but not *which ones your hardware can handle*\n* **Hardware requirement tables** are usually static, incomplete, or model-specific\n* **Manual checking** requires juggling VRAM, RAM, quantization, and disk estimates yourself\n\nThis tool:\n\n* Centralizes model data\n* Automates system inspection\n* Provides a single compatibility view tailored to *your* machine\n\nIt doesn’t replace benchmarks, but it **dramatically shortens the trial-and-error phase**.\n\n**Key Features**\n\n* Automatic hardware detection (CPU, RAM, GPU, disk)\n* 200+ supported models (Llama, Mistral, Qwen, Gemma, Code models, Vision models, embeddings)\n* NVIDIA & AMD GPU support (including multi-GPU systems)\n* Compatibility scoring based on real resource constraints\n* Human-readable report output (`ai_capability_report.txt`)\n\n**Example Output**\n\n    ✓ CPU: 12 cores\n    ✓ RAM: 31.11 GB available\n    ✓ GPU: NVIDIA GeForce RTX 5060 Ti (15.93 GB VRAM)\n\n    ✓ Retrieved 217 AI models\n    ✓ You can run 158 out of 217 models\n    ✓ Report generated: ai_capability_report.txt\n\n**How It Works (High Level)**\n\n1. Analyze system hardware\n2. Fetch AI model requirements (parameters, quantization, RAM/VRAM, disk)\n3. Score compatibility based on available resources\n4. Generate recommendations and optimization tips\n\n**Tech Stack**\n\n* Python 3.7+\n* psutil, requests, BeautifulSoup\n* GPUtil (GPU detection)\n* WMI (Windows support)\n\nWorks on **Windows, Linux, and macOS**.\n\n**Limitations**\n\n* Compatibility scores are estimates, not guarantees\n* VRAM detection can vary depending on drivers and OS\n* Optimized mainly for NVIDIA and AMD GPUs\n\nActual performance still depends on model implementation, drivers, and system load."}
{"instruction": "I built a Python IDE that runs completely in your browser (no login, fully local)", "input": "", "output": "I built a Python IDE that runs completely in your browser (no login, fully local)\nI've been working on this browser-based Python compiler and just want to share it in case anyone finds it useful: [https://pythoncompiler.com](https://pythoncompiler.com/)\n\nWhat's different about it:\n\nFirst of all, Everything runs in your browser. Your code literally never touches a server. It has a nice UI, responsive and fast, hope you like it.. Besides, has some good features as well:\n\n\\- Supports regular code editor + ipynb notebooks (you can upload your notebook and start working as well)\n\n\\- Works with Data science packages like pandas, matplotlib, numpy, scikit-learn etc.\n\n\\- Can install PyPI packages on the fly with a button click.\n\n\\- Multiple files/tabs support\n\n\\- Export your notebooks to nicely formatted PDF or HTML (this is very handy personally).\n\n\\- Super fast and saves your work every 2 seconds, so your work wont be lost even if you refresh the page.\n\nWhy I built it:\n\nPeople use python use online IDEs a lot but they are way too simple. Been using it myself for quick tests and teaching. Figured I'd share in case it's useful to anyone else. All client-side, so your code stays private.\n\nWould love any feedback or suggestions! Thanks in advance."}
{"instruction": "rustdash: Lodash-style utilities for Python, Rust-powered (10-100x faster on complex ops)", "input": "", "output": "rustdash: Lodash-style utilities for Python, Rust-powered (10-100x faster on complex ops)\n# What My Project Does\n\n**rustdash** is a Lodash-inspired utility library for Python data manipulation, powered by Rust via PyO3:\n\n    pythonimport rustdash as _\n\n    # Array utilities (9 functions)\n    _.chunk([1,2,3,4,5], 2)\n    # [[1,2], [3,4], [5]]\n    _.flatten_deep([[1],[2,[3]]])\n    # [1, 2, 3]\n    _.compact([1, None, 2])\n    # [1, 2]\n\n    # Object utilities w/ JSONPath wildcards (7 functions)\n    data = {\"users\": [{\"name\": \"Alice\"}, {\"name\": \"Bob\"}]}\n    _.get_all(data, \"users[*].name\")\n    # [\"Alice\", \"Bob\"]\n    _.has_all(data, \"users[*].name\")\n    # True\n    _.pick(data, [\"users\"])\n    # {\"users\": [...]}\n\n\n**Live on PyPI:** `pip install rustdash`\n\n# Target Audience\n\n**Data engineers, API developers, ETL workflows** who:\n\n* Process JSON/API responses daily\n* Need Lodash-style helpers (`chunk`, `pick`, `flatten`)\n* Want Rust performance on recursive ops (9.6x faster `flatten_deep`)\n* Work with nested data but hate verbose `dict.get()` chains\n\n# Comparison\n\n|Feature|rustdash|pydash|pure Python|\n|:-|:-|:-|:-|\n|`flatten_deep` (10k)|**15ms**|173ms|139ms|\n|JSONPath `users[*].name`|✅ **Native**|❌ No|❌ No|\n|PyPI wheels|✅ All platforms|✅|N/A|\n|Rust performance|✅ Complex ops|❌ Pure Python|❌ Pure Python|\n\n**rustdash = pydash API + Rust speed on what matters** (recursive array/object ops).\n\n**Full benchmarks:** [https://pypi.org/project/rustdash/#description](https://pypi.org/project/rustdash/#description)\n\n# Links\n\n* PyPI: [https://pypi.org/project/rustdash/](https://pypi.org/project/rustdash/)\n* GitHub: [https://github.com/GonzaloJCY/rustdash](https://github.com/GonzaloJCY/rustdash)\n* Examples: [https://github.com/GonzaloJCY/rustdash/blob/main/examples/demo.py](https://github.com/GonzaloJCY/rustdash/blob/main/examples/demo.py)\n\n# 🙏 Feedback I'm seeking\n\n**Try it on your JSON/API data and tell me:**\n\n1. What Lodash functions do you miss most? (`set`, `unset`, `intersection`?)\n2. Rough edges with `get_all(\"users[*].name\")` syntax?\n3. Performance surprises (good or bad)?\n\n**Feature requests:** [https://github.com/GonzaloJCY/rustdash/discussions/categories/feature-requests](https://github.com/GonzaloJCY/rustdash/discussions/categories/feature-requests)"}
{"instruction": "What's the best async-native alternative to Celery for I/O-heavy workloads?", "input": "", "output": "What's the best async-native alternative to Celery for I/O-heavy workloads?\nI am a developer of [Rhesis.ai](http://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.\n\nThe question is: how can we parallelize this more effectively?\n\nCurrently, 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.\n\nThe 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.\n\nWhat 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.\n\nFastAPI 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.\n\nSo 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).\n\nWe 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.\n\nFinally, 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."}
{"instruction": "I wrote a free, open-source book: \"Advanced Methods in SciPy and Statsmodels\"", "input": "", "output": "I wrote a free, open-source book: \"Advanced Methods in SciPy and Statsmodels\"\nI wrote a free, open-source book: \"Advanced Methods in SciPy and Statsmodels\"\n\n  SciPy and statsmodels documentation tells you how to call a function. This book tells you what that function does and why it works.\n\n  23 chapters covering optimization, Monte Carlo methods, likelihood inference, time series, survival analysis, and causal inference — each with:\n\n  - The mathematical theory explaining WHY the method works (not just the formula — the intuition that changes how you think about it)\n  - From-scratch Python implementations verified against the library output\n  - Diagnostics showing how to detect when the method fails\n  - 92 exercises with full worked solutions\n\n  The book fills the gap between \"read the docs\" and \"read the textbook.\" If you've ever wondered why scipy.optimize.minimize defaults to BFGS,\n  why statsmodels uses HC1 for robust standard errors, why the bootstrap fails for the sample maximum, or why two-way fixed effects gives wrong\n  answers under staggered adoption — this book explains it with code you can run.\n\n  147,000 words. All code executes in a pinned Python environment. Free to read online, source on GitHub.\n\n  Read it: https://kundeng.github.io/bayeslearner-scikit-refresh/\n  Source: https://github.com/kundeng/bayeslearner-scikit-refresh"}
{"instruction": "I ported PyMuPDF4LLM to Go/C, and made it 100x faster (literally), while keeping comparable quality", "input": "", "output": "I ported PyMuPDF4LLM to Go/C, and made it 100x faster (literally), while keeping comparable quality\nHi all,\n\nI've posted this before. Two times. Last time I tried posting, I used AI for the post, and it got removed. Now, I've realised that it kinda makes the post bad. I've changed lots of things, and I'd like to share it.\n\nI don't know how to structure this. First, thanks for reading.\n\nThis all started when I was building a cyber-security-related RAG tool for companies with my Dad. I'm only 15, and so, I was actually quite surprised he trusted me to help him. I had some NIST and ISO documents. I wanted a PDF parser. The fastest tool I could find was PyMuPDF4LLM. I wasn't even looking for \"stupidly fast\", just bearably fast. Docling, Marker, etc were.. way too slow. Even for small PDFs.\n\nBut as I increased my dataset, I got annoyed anyway. It took too long, and the only faster options were libraries like PyMuPDF and Pdfium. But those were just basic text extraction. No tables or formatting. I was told that for this level of quality, you had to bite the bullet and deal with slow extraction.\n\nI thought, \"what if you didn't have to?\"\nMy idea was: PyMupDF4llm uses Pymupdf, which uses Mupdf. C is faster than Python. Rewrite Pymupdf4llm in C through mupdf, then bind it back to python.\n\n**This worked.**\n\nAnd.. then I got annoyed of C. So I ported it to Go. I know. Silly.\n\nAnyway, now, I bench-marked this, (4800H, all eight cores).\n\n**About 1000 pages/s on a 1600 page document, and 500 pages/s on a 149 page document.** *^ there are more details on the GitHub, and you are free to test yourself. (to be honest, i don't know how to provide \"real\" benchmarks).*\n\nI don't even know HOW it even got THAT fast. Was never my intention.\n\nIt was supposed to be a direct port; like matching output. Then I steered away cause it was impossible. But I was still trying to make it output Markdown.\n\nThen I thought, that, why not structured output, like JSON? It's easier to parse for RAG, lets you add WAY more data. And, you can still convert it to Markdown or ANY other format in the end!\n\nNow, about quality; it's obviously not as good as Docling, Marker, etc. It doesn't do OCR or ML. But in my opinion, it's comparable to PyMuPDF4LLm, which certainly isn't bad. And that was my purpose. It was a choice.\n\n## What this is\nA fast alternative to PyMuPDF4LLM, Docling, Marker, and others, outputting structured JSON with additional details.\n\n## Target audience\nPretty much anybody that already uses PyMuPDF4LLM, anybody in RAG with digital documents, or anywhere where you have a decent amount of PDFs and you want to process them\n\n## Comparison table\n\n| Tool            | Speed (pps) | Tables | Images (Figures)                                  | OCR (Y/N)     | JSON Output      | Best For              |\n| --------------- | ----------- | ------ | ------------------------------------------------- | ------------- | ---------------- | --------------------- |\n| pymupdf4llm-C   | ~500        | Yes    | No (WIP)                                          | N             | Yes (structured) | RAG, high volume      |\n| pymupdf4llm     | ~10         | Yes    | Yes (but not ML to get contents)                  | N             | Markdown         | General extraction    |\n| pymupdf (alone) | ~250        | No     | No, not by itself, requires more effort I believe | N             | No (text only)   | basic text extraction |\n| marker          | ~0.5-1      | Yes    | Yes (contents with ML?)"}
{"instruction": "NServer 3.2.0 Released", "input": "", "output": "NServer 3.2.0 Released\nHeya r/python 👋\n\nI've just released [NServer](https://github.com/nhairs/nserver) `v3.2.0`\n\n# About NServer\n\nNServer is a Python framework for building customised DNS name servers with a focuses on ease of use over completeness. It implements high level APIs for interacting with DNS queries whilst making very few assumptions about how responses are generated.\n\n**Simple Example:**\n\n```\nfrom nserver import NameServer, Query, A\n\nserver = NameServer(\"example\")\n\n@server.rule(\"*.example.com\", [\"A\"])\ndef example_a_records(query: Query):\n    return A(query.name, \"[IP]\")\n```\n\n# What's New\n\nThe biggest change in this release was implementing concurrency through multi-threading.\n\nThe application already handled TCP multiplexing, however all work was done in a single thread. Any blocking call (e.g. database call) would ruin the performance of the application.\n\nThat's not to say that a single thread is bad though - for non-blocking responses, the server can easily handle 10K requests per second. However a blocking response of 10-100ms will bring that rate down to 25rps.\n\nFor the multi-threaded application we use 3 sets of threads:\n\n- A single thread for receiving queries\n- A configurable amount of threads for workers that process the requests\n- A single thread for sending responses\n\nEven though there are only two threads dedicated to sending and receiving this does not appear to be the main bottleneck. I suspect that the real bottleneck is the context switching between threads.\n\nIn theory using asyncio might be more performant due to the lack of context switches - the library itself is all sync so would require extensive changes to either support or move to fully async code. I don't think I'll work on this any time soon though as 1. I don't have experience with writing async servers and 2. the server is actually really performant.\n\nWith multi-threading we could achieve ~300-1200 rps with the same 10-100ms delay.\n\n[Although the code changes](https://github.com/nhairs/nserver/pull/14) themselves are relatively straightforward. It's the benchmarking that posed the most issues.\n\nTrying to benchmark from the same host as the server tended to completely fail when using TCP although UDP seemed to be fine. I suspect there is some implementation detail of the local networking stack that I'm just not aware of.\n\n[Once we could actually get some results](https://github.com/nhairs/nserver/pull/14#issuecomment-[PHONE]) it was somewhat suprising the performance we were achieving. Although 1-2 orders of magnitude slower than a non-blockin server running on a single thread, it turns out that we could get better TCP performance with NServer directly instead of using CoreDNS as a reverse-proxy - load-balancer. It also reportedly ran better than some other DNS servers written in C.\n\nOverall I gotta say that I'm pretty happy with how this turned out. In particular the modular internal API design that I did a while ago to enable changes like this ended up working really well - I only had to change a small amount of code outside of the multi-threaded application."}
{"instruction": "FastAPI app.frontend(): serving a frontend build from the same Python app", "input": "", "output": "FastAPI app.frontend(): serving a frontend build from the same Python app\nI wrote [a practical article](https://modernpython.io/serving-a-frontend-with-fastapi-a-practical-guide/) about FastAPI's `app.frontend()` feature.\n\nThe interesting bit is that it serves static frontend build output as low-priority routes, so normal FastAPI API endpoints still win.\n\nThe article covers:\n\n* `app.frontend(\"/\", directory=\"dist\")`\n* SPA fallback with `fallback=\"index.html\"`\n* how it differs from `StaticFiles`\n* serving under a prefix with `APIRouter`\n* a complete mini dashboard example with FastAPI + vanilla JS"}
{"instruction": "Don't make your package repos trusted publishers", "input": "", "output": "Don't make your package repos trusted publishers\nA lot of Python projects have a GitHub Action that's configured as a trusted publisher. Some action such as a tag push, a release or a PR merge to main triggers the release process, and ultimately leads to publication to Pypi. This is what I'd been doing until recently, but it's not good.\n\nIf your project repo is a trusted publisher, it's a single point of failure with a huge attack surface. There are a lot of ways to compromise Github Actions, and a lot of small problems can add up. Are all your actions referencing exact commits? Are you ever referencing PR titles in template text? etc.\n\nIt's much safer to just have your package repo publish a release and have your workflow upload the release artifacts to it. Then you can have a wholly separate private repo that you register as the trusted publisher. Importantly though *don't trigger the release automatically*. You can have one script on your machine that does both, but don't let the Github repo push some tag or something that will automatically be picked up by the release machinery.\n\nThis would have prevented the original Trivy attack, and also prevented the LiteLLM attack that followed from it. Someone will have to actually attack your machine, and even then they have to get into Github 2fa, before they can release an infected package as you."}
{"instruction": "sdsort, a utility to sort functions and methods according to the step-down rule", "input": "", "output": "sdsort, a utility to sort functions and methods according to the step-down rule\n>Whenever the literary German dives into a sentence, this is the last you are going to see of him till he emerges on the other side of his Atlantic with his verb in his mouth.\n— *Mark Twain*\n\nThis quote often comes to mind when I read code nowadays.\n\nMore often than not, files are organized so that functions are defined *before* they are called. The source file starts by listing all the nitty-gritty details. It’s not until you reach the very end of the file that you finally get to see the big picture—much like never knowing what a German sentence means until you reach the verb lurking at the very end!\n\nI’ve reviewed a fair share of Pull Requests in my life. More than once, I’ve found myself writing comments on all sorts of implementation details, only to realize later that they didn't matter because overall solution method needs a rethink, something which only became obvious once I reached the end of the file.\n\nHaving to build up an entire mental model from the ground up before understanding how everything fits together can be wasteful. The **Step-Down Rule** from *Clean Code* addresses this directly. When developers adhere to it, the code that is at the highest level of abstraction ends up at the top of the file (well, just below the imports).\n\n# What My Project Does\n\n`sdsort` (Step-Down Sort) is a command-line tool that automatically rearranges your Python source code so that function calls appear *before* their corresponding function definitions.\n\nBy sorting the file this way, the high-level \"big picture\" logic naturally floats to the top of the file, making it the first thing a developer reads, while the implementation details are pushed further down.\n\nIf you are using **uv**, running it is dead simple:\n\n    uvx sdsort <path_to_your_file_or_folder>\n\n*(You can also just pip install sdsort if you prefer the classic way).*\n\n# Target Audience\n\nThis is meant for Python developers and teams who prefer reading code in a top-down execution order rather than a bottom-up implementation order.\n\n# Comparison\n\nWhile there are IDE plug-ins like [https://plugins.jetbrains.com/plugin/11005-clean-code-method-rearranger](https://plugins.jetbrains.com/plugin/11005-clean-code-method-rearranger) that can do this for other programming languages (e.g. Java), I'm not aware of an existing CLI tool that sorts Python functions/methods according to the step-down rule.\n\nThis tool is best used before formatting, so I recommend running it before running black/ruff/yapf.\n\n# Links\n\n* **PyPI:**[https://pypi.org/project/sdsort/](https://pypi.org/project/sdsort/)\n* **GitHub:** [https://github.com/eirikurt/sdsort](https://github.com/eirikurt/sdsort)\n\nPlease let me know if you find it useful, or file an issue if you run into any bugs or edge cases so that I can get them *sorted*\\*\n\n\n\n\\* I'm not ashamed to admit that I enjoy bad puns"}
{"instruction": "I made a small local-first embedded database in Python (hvpdb)", "input": "", "output": "I made a small local-first embedded database in Python (hvpdb)\nWhat My Project Does\n\nhvpdb is a local-first embedded NoSQL database written in Python.\n\nIt is designed to be embedded directly into Python applications, focusing on:\n\npredictable behavior\n\nexplicit trade-offs\n\nminimal magic\n\nsimple, auditable internals\n\nThe goal is not to replace large databases, but to provide a small embedded data store that developers can reason about and control.\n\n---\n\nTarget Audience\n\nhvpdb is intended for:\n\ndevelopers building local-first or embedded Python applications\n\nprojects that need local storage without running an external database server\n\nusers who care about understanding internal behavior rather than abstracting everything away\n\nIt is suitable for real projects, but still early and evolving.\nI am already using it in my own projects and looking for feedback from similar use cases.\n\n---\n\nComparison\n\nCompared to common alternatives:\n\nSQLite:\nhvpdb is document-oriented rather than relational, and focuses on explicit control and internal transparency instead of SQL compatibility.\n\nTinyDB:\nhvpdb is designed with stronger durability, encryption, and performance considerations in mind.\n\nServer-based databases (MongoDB, Postgres):\nhvpdb does not require a separate server process and is meant purely for embedded/local use cases.\n\n---\n\nYou can try it via pip:\n```python\npip install hvpdb\n```\n\nIf you find anything confusing, missing, or incorrect, please open a GitHub issue — real usage feedback is very welcome.\n\nRepo: https://github.com/8w6s/hvpdb\n\n---"}
{"instruction": "Async Tasks in Production", "input": "", "output": "Async Tasks in Production\nI have few apis with some endpoints that need to follow async pattern. Typically, this is just a db stored proc call that can take anywhere between 5-20 minutes but few cases where we have some jobs that require compute. These use cases for worker-job come up a lot in my apis.\n\n\nWondering what people are doing for async jobs. I know celery-redis seems popular wondering how you guys are running that in production especially if you have many different   apis requiring different jobs."}
{"instruction": "༄ streamable - sync/async iterable streams for Python", "input": "", "output": "༄ streamable - sync/async iterable streams for Python\n[https://github.com/ebonnal/streamable](https://github.com/ebonnal/streamable)\n\n# What my project does\n\nA `stream[T]` wraps any `Iterable[T]` or `AsyncIterable[T]` with a lazy fluent interface covering concurrency, batching, buffering, rate limiting, progress observation, and error handling.\n\nChain lazy operations:\n\n    import logging\n    from datetime import timedelta\n    import httpx\n    from httpx import Response, HTTPStatusError\n    from streamable import stream\n\n    pokemons: stream[str] = (\n        stream(range(10))\n        .map(lambda i: f\"https://pokeapi.co/api/v2/pokemon-species/{i}\")\n        .throttle(5, per=timedelta(seconds=1))\n        .map(httpx.get, concurrency=2)\n        .do(Response.raise_for_status)\n        .catch(HTTPStatusError, do=logging.warning)\n        .map(lambda poke: poke.json()[\"name\"])\n    )\n\nConsume it (sync or async):\n\n    >>> list(pokemons)\n    ['bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise']\n\n    >>> [pokemon async for pokemon in pokemons]\n    ['bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise']\n\n# Target Audience\n\nIf you find yourself writing verbose iterable plumbing, `streamable` will probably help you keep your code expressive, concise, and memory-efficient.\n\n* You may need **advanced behaviors** like time-windowed grouping by key, concurrent flattening, periodic observation of the iteration progress, buffering (decoupling upstream production rate from downstream consumption rate), [*etc*.](https://github.com/ebonnal/streamable/tree/main?tab=readme-ov-file#-operations-docs)\n* You may want a **unified interface for sync and async** behaviors, e.g. to switch seamlessly between `httpx.Client.get` and `httpx.AsyncClient.get` in your `.map`  (or anywhere else), consume the `stream` as a sync or as an async iterable, from sync or async context.\n* You may simply want to chain `.map`s and `.filter`s **without overhead** vs `builtins.map` and `builtins.filter`.\n\n# Comparison\n\nAmong similar libraries, `streamable`'s proposal is an interface that is:\n\n* **pythonic** (who am I to state that, though): Not porting features from another language. It's a dozen expressive operations trying to focus on Python developers' needs.\n* **unifying sync and async**: Create streams that are both `Iterable` and `AsyncIterable`, with operations adapting their behavior to the type of iteration and accepting sync and async functions.\n\nThe [README](https://github.com/ebonnal/streamable) gives a complete tour of the library, and I’m also happy to answer any questions you may have in the comments.\n\nAbout 18 months ago I presented [here the 1.0.0.](https://www.reddit.com/r/Python/comments/1fp38jd/streamable_streamlike_manipulation_of_iterables/)\nI'm glad to be back to present this matured 2.0.0 thanks to your feedback and contributions!"}
{"instruction": "PyTexas 2026 is this weekend (Apr 18th-19th) at Austin's beautiful central library.", "input": "", "output": "PyTexas 2026 is this weekend (Apr 18th-19th) at Austin's beautiful central library.\nMore info at https://www.pytexas.org/2026/\n\nTutorials start tomorrow (Friday) during the day, but the main conference is Saturday and Sunday. I just got into town and will be giving a talk, but also handing out my Python-generated *Choose Your Own Adventure Tic Tac Toe Zine* It's still not too late to get tickets!"}
{"instruction": "Handling Errors as Values in Python with Katharos", "input": "", "output": "Handling Errors as Values in Python with Katharos\nHi guys this tutorial is about handling errors as exception in Python or nerdy language monadic error handling pattern in Python using [katharos](https://github.com/kamalfarahani/katharos) library:\n\n[https://theblog.info/posts/handling-errors-as-values-in-python-with-katharos](https://theblog.info/posts/handling-errors-as-values-in-python-with-katharos)"}
{"instruction": "2026 Python Developers Survey", "input": "", "output": "2026 Python Developers Survey\nThe official Python Developers Survey, conducted in partnership with [JetBrains](https://www.jetbrains.com/), is currently open.\n\nThe survey is a joint initiative between the Python Software Foundation and JetBrains.\n\nBy participating in the 2026 survey, you not only stand a chance to win one of twenty (20) **$100 Amazon Gift Cards**, but more significantly, you provide valuable data on Python's usage.\n\n[Take the survey now](https://surveys.jetbrains.com/s3/python-developers-survey-2026)—it takes less than 15 minutes to complete."}
{"instruction": "Career change to Python developer at 40, a good idea ?", "input": "", "output": "Career change to Python developer at 40, a good idea ?\nI am French, I live in Paris, I am 40 years old, I previously worked in sales and I would like to change careers to become a Python developer. I am going to start an intensive program at a school called École 42, which is free of charge. This school is open 24/7 and will teach us Python and AI.\nToday, there are many opportunities in AI, which is why I chose this path. I do not have a degree and I am very bad at mathematics. I am doing this program in order to create my own company. At this school, there are around 700 people learning the same things, with group projects to complete. There are daily events, both related to software development and entrepreneurship. There is also the possibility of joining an entrepreneurship incubator called Station F.\nI know I will never become a great developer, but my real goal is to understand how software development works, the tech environment, and above all to take part in events and build my own projects, eventually leading to a company to which I will dedicate 15 hours a day. What do you think?"}
{"instruction": "Why I stopped trying to build a \"Smart\" Python compiler and switched to a \"Dumb\" one.", "input": "", "output": "Why I stopped trying to build a \"Smart\" Python compiler and switched to a \"Dumb\" one.\nI've been obsessed with Python compilers for years, but I recently hit a wall that changed my entire approach to distribution.\n\nI used to try the \"Smart\" way (Type analysis, custom runtimes, static optimizations). I even built a project called Sharpython years ago. It was fast, but it was useless for real-world programs because it couldn't handle numpy, pandas, or the standard library without breaking.\n\nI realized that for a compiler to be useful, **compatibility is the only thing that matters.**\n\n**The Problem:**\nCurrent tools like Nuitka are amazing, but for my larger projects, they take **3 hours** to compile. They generate so much C code that even major compilers like Clang struggle to digest it.\n\n**The \"Dumb\" Solution:**\nI'm experimenting with a compiler that maps CPython bytecode directly to C glue-logic using the libpython dynamic library.\n\n* **Build Time:** Dropped from 3 hours to **under 5 seconds** (using TCC as the backend).\n* **Compatibility:** 100% (since it uses the hardened CPython logic for objects and types).\n* **The Result:** A standalone executable that actually runs real code.\n\nI'm currently keeping the project private while I fix some memory leaks in the C generation, but I made a technical breakdown of why this \"Dumb\" approach beats the \"Smart\" approach for build-time and reliability.\n\nI'd love to hear your thoughts on this. Is the 3-hour compile time a dealbreaker for you, or is it just the price we have to pay for AOT Python?\n\n\n**Technical Breakdown/Demo:** [https://www.youtube.com/watch?v=NBT4FZjL11M](https://www.youtube.com/watch?v=NBT4FZjL11M)"}
{"instruction": "trueform v0.7: extends NumPy arrays with geometric types for vectorized spatial queries", "input": "", "output": "trueform v0.7: extends NumPy arrays with geometric types for vectorized spatial queries\nv0.7 of [trueform](https://trueform.polydera.com) gives NumPy arrays geometric meaning. Wrap a `(3,)` array and it's a Point. `(2, 3)` is a Segment. `(N, 3)` is N points. Eight primitives (Point, Line, Ray, Segment, Triangle, Polygon, Plane, AABB) and three forms (Mesh, EdgeMesh, PointCloud) backed by spatial and topological structures. Every query broadcasts over batches the way you'd expect, in parallel.\n\n```bash\npip install trueform\n```\n\n```python\nimport numpy as np\nimport trueform as tf\n\nmesh = tf.Mesh(*tf.read_stl(\"dragon.stl\"))\n\n# signed distance from every vertex to a plane through the centroid\nplane = tf.Plane(normal=np.float32([1, 2, 0]), origin=mesh.points.mean(axis=0))\nscalars = tf.distance(tf.Point(mesh.points), plane)  # shape (num_verts,)\n```\n\nSame function, different target. Swap the plane for a mesh, the tree builds on first query:\n\n```python\nmesh_b = tf.Mesh(*tf.read_stl(\"other.stl\"))\ndistances = tf.distance(tf.Point(mesh.points), mesh_b)  # shape (num_verts,)\n```\n\nTwo meshes, not touching. Find the closest pair of surface points and bring them together without collision:\n\n```python\ntf.intersects(mesh, mesh_b)  # False\n\n(id_a, id_b), (dist2, pt_a, pt_b) = tf.neighbor_search(mesh, mesh_b)\n\n# translate mesh_b towards mesh, leave a small gap\ndirection = pt_a - pt_b\nT = np.eye(4, dtype=np.float32)\nT[:3, 3] = direction * (1 - 0.01 / np.sqrt(dist2))\nmesh_b.transformation = T\n\ntf.intersects(mesh, mesh_b)  # still False, tree reused, transform applied at query time\n```\n\nVoxelize a mesh. Build a grid of bounding boxes, check which ones the mesh occupies:\n\n```python\nlo, hi = mesh.points.min(axis=0), mesh.points.max(axis=0)\ngrid = np.mgrid[lo[0]:hi[0]:100j, lo[1]:hi[1]:100j, lo[2]:hi[2]:100j].reshape(3, -1).T.astype(np.float32)\nstep = ((hi - lo) / 100).astype(np.float32)\nvoxels = tf.AABB(min=grid, max=grid + step)\noccupied = tf.intersects(mesh, voxels)  # shape (1000000,) bool\n```\n\nDepth map. Cast a grid of rays downward:\n\n```python\nxy = np.mgrid[lo[0]:hi[0]:500j, lo[1]:hi[1]:500j].reshape(2, -1).T.astype(np.float32)\norigins = np.column_stack([xy, np.full(250000, hi[2] + 0.1, dtype=np.float32)])\nrays = tf.Ray(origin=origins, direction=np.tile([0, 0, -1], (250000, 1)).astype(np.float32))\n\nface_ids, ts = tf.ray_cast(rays, mesh, config=(0.0, 10.0))\ndepth_map = ts.reshape(500, 500)  # NaN where no hit\n```\n\nThe scalar field from the first example feeds directly into cutting. Isobands slices along threshold values, returns per-face labels and intersection curves:\n\n```python\n(cut_faces, cut_points), labels, (paths, curve_pts) = tf.isobands(\n    mesh, scalars, [0.0], return_curves=True\n)\n\ncomponents, component_ids = tf.split_into_components(\n    tf.Mesh(cut_faces, cut_points), labels\n)\nbottom_faces, bottom_points = components[0]\ntop_faces, top_points = components[1]\n\n# triangulate the curves to cap the cross-section\ncap_faces, cap_points = tf.triangulated((paths, curve_pts))\n```\n\nNumPy in, NumPy out. C++ backend, parallelized across cores.\n\n[Documentation](https://trueform.polydera.com/py/getting-started) · [GitHub](https://github.com/polydera/trueform) · [Benchmarks](https://trueform.polydera.com/py/benchmarks)"}
{"instruction": "Making Pyrefly's Diagnostics 18x Faster", "input": "", "output": "Making Pyrefly's Diagnostics 18x Faster\nHigh performance on large codebases is one of the main goals for Pyrefly, a next-gen language server & type checker for Python implemented in Rust.\n\nIn this blog post, we explain how we optimized Pyrefly's incremental rechecks to be 18x faster in some real-world examples, using fine-grained dependency tracking and streaming diagnostics.\n\n[Full blog post](https://pyrefly.org/blog/2026/02/06/performance-improvements/)\n\n[Github](https://github.com/facebook/pyrefly)"}
{"instruction": "I built a linter that checks if your Python code has good vibes. Then I ran it on 12 famous repos.", "input": "", "output": "I built a linter that checks if your Python code has good vibes. Then I ran it on 12 famous repos.\nNo one was ready.\n\n[flake8-vibes](https://github.com/DannyIsYog/vibe-checker) is a Flake8 plugin that performs vibe analysis on your codebase. Unlike regular linters that care about correctness and style, this one focuses on what really matters: whether your code is okay, emotionally.\n\n**What My Project Does:** It has 87 rules across several categories like naming crimes, boolean chaos, exception dishonesty, and temporal risk. My personal favourite is VIB001, which uses git blame to find large functions written on a Thursday - a liminal space too close to Friday to think clearly, too far from Monday to care. It also ships with a CLI (`vibe-check .`) and a VS Code extension with inline ghost text, hover messages, and a \"Check Workspace\" command that gives you the full breakdown without leaving the editor.\n\n**Target Audience:** Developers who want to ~~suffer~~ slay in a new way. It's a toy project - don't use it in production unless your production deserves it.\n\n**Comparison:** Tools like `pylint`, `flake8`, and `ruff` check whether your code is correct or well-styled. `flake8-vibes` checks whether your code has good energy. There is no overlap. No existing linter will tell you that your function was written on a Thursday and that it's a problem. This one will.\n\nHere's what happened when I ran it on some of the most beloved Python repos:\n\n|Repo|Files|Violations|Score|Verdict|\n|:-|:-|:-|:-|:-|\n|[django](https://github.com/django/django)|902|8,801|51/100|concerning|\n|[flask](https://github.com/pallets/flask)|24|608|0/100|cooked|\n|[fastapi](https://github.com/tiangolo/fastapi)|48|1,066|0/100|cooked|\n|[pandas](https://github.com/pandas-dev/pandas)|1,414|56,653|0/100|expired|\n|[scikit-learn](https://github.com/scikit-learn/scikit-learn)|631|26,277|0/100|cooked|\n|[transformers](https://github.com/huggingface/transformers)|2,476|54,012|0/100|cooked|\n|[pip](https://github.com/pypa/pip)|401|5,907|26/100|this is a cry for help|\n|[ruff](https://github.com/astral-sh/ruff)|14|136|51/100|the vibes are questionable|\n|[pytest](https://github.com/pytest-dev/pytest)|73|1,734|0/100|it's giving dumpster fire|\n|[bottle](https://github.com/bottlepy/bottle)|30|1,561|0/100|cooked|\n|[requests](https://github.com/psf/requests)|18|413|0/100|it's giving dumpster fire|\n|[rich](https://github.com/Textualize/rich)|100|1,552|22/100|cooked|\n\nDjango and Ruff are the only ones that cleared 50. Ruff lints everything except, apparently, itself. Pandas has 56,653 violations, which tracks.\n\n**Is your code slaying and vibing?** Find out in one command:\n\n    pip install flake8-vibes && vibe-check .\n\nIf so, don't forget to add the badge to your README!\n\n[Check the repo to know more](https://github.com/DannyIsYog/vibe-checker)\n\n`flake8-vibes` *does not make claims about your mental health, work-life balance, or professional conduct. It makes claims about your code. These are different things, mostly.*\n\n*This project was inspired by* [*scx\\_horoscope*](https://github.com/zampierilucas/scx_horoscope) *and was built using* [*Claude*](https://claude.ai)*.*"}
{"instruction": "Python iOS UI development", "input": "", "output": "Python iOS UI development\nHey there,\n\nfor the people using PySide for UI applications, after having solely Android support, there was a new announcement that iOS is now supported, and will be available in the upcoming PySide release:\n[https://www.qt.io/blog/python-mobile-app-development-bringing-pyside6-on-ios](https://www.qt.io/blog/python-mobile-app-development-bringing-pyside6-on-ios)\n\nI have been following the work by the BeeWare project, which has been providing iOS support for some time now: [https://toga.beeware.org/en/latest/reference/platforms/iOS/](https://toga.beeware.org/en/latest/reference/platforms/iOS/) and recently the work from the Flet team as well: [https://flet.dev/blog/flet-for-ios/](https://flet.dev/blog/flet-for-ios/)\n\n\nWhat I wanted to achieve with this post, is to know any project that you know is currently on iOS and developed with Python and some UI framework, because time to time we see nice \"calculator app\" being showcases in places, but a more official application of something is what I have been failing to find.\n\nOf course, the goal of \"I have my code here, and I just want to deploy it to iOS\" is completely understandable, but I see haven't found some very cool apps somewhere, that we know are based on Python.\n\nLast but not least, I guess you have been noticed that starting from 3.15 we will be able to download Python for iOS from python.org: https://www.python.org/downloads/ios/"}
{"instruction": "Made a networking library for multiplayer games -- pump() once per frame and forget about sockets", "input": "", "output": "Made a networking library for multiplayer games -- pump() once per frame and forget about sockets\n**TL;DR:** I built `repod`, a networking library for Python games (Pygame, Raylib, Arcade). No `async`/`await` boilerplate in your game loop—just send/receive dicts and call `pump()` once per frame.\n\n**repod** is a high-level networking library designed for real-time multiplayer games. It abstracts away the complexity of `asyncio` and sockets, allowing developers to handle network events through simple class methods.\n\nInstead of managing buffers or coroutines, you simply:\n\n1. Subclass a `Channel` (server) or `ConnectionListener` (client).\n2. Write methods starting with `Network_` (e.g., `Network_move`).\n3. Call `pump()` once per frame in your main loop to dispatch all pending messages.\n\nIt uses **msgpack** for fast serialization and length-prefix framing to ensure data integrity.\n\n# Target Audience\n\nThis is currently meant for **indie developers, hobbyists, and game jam participants**.\n\n* **Current Status:** Early stages (v0.1.2), but stable enough for projects.\n* **Goal:** It's perfect for those who want to add multiplayer to a Pygame/Raylib project without restructuring their entire codebase around an asynchronous architecture.\n\n# Comparison\n\nCompared to other solutions:\n\n* **vs. Raw Sockets/Asyncio:** Much higher level. No need to handle partial packets, byte encoding, or event loop management.\n* **vs. PodSixNet:** It’s essentially a modern spiritual successor. While PodSixNet is broken on Python 3.12+ (due to the removal of `asyncore`), **repod** uses a modern `asyncio` backend while keeping the same easy-to-use API.\n* **vs. Twisted/Autobahn:** Much lighter. It doesn't force a specific framework on you; it just sits inside your existing `while True` loop.\n\n# Quick Example (Server)\n\nPython\n\n    from repod import Channel, Server\n\n    class GameChannel(Channel):\n        def Network_chat(self, data: dict) -> None:\n            # Broadcasts: {\"action\": \"chat\", \"msg\": \"hello\"}\n            self.server.send_to_all({\"action\": \"chat\", \"msg\": data[\"msg\"]})\n\n    class GameServer(Server):\n        channel_class = GameChannel\n\n    GameServer(host=\"[IP]\", port=5071).launch()\n\n\n# Links & Info\n\n* **PyPI:** `pip install repodnet` (Import as `repod`)\n* **Docs:** [https://walkercito.github.io/repod](https://walkercito.github.io/repod)\n* **Repo:** [https://github.com/Walkercito/repod](https://github.com/Walkercito/repod)\n* **License:** LGPL v3\n\nI've included examples in the repo for a chat room, a shared whiteboard (pygame-ce), and Pong with server-authoritative physics. I'd love to hear your thoughts or what features you'd like to see next!"}
{"instruction": "TIL: Dict Patterns Don't Match Dict Shapes", "input": "", "output": "TIL: Dict Patterns Don't Match Dict Shapes\nTL;DR: Unlike sequence patterns (which require an exact shape match), pattern matching on dictionaries simply ignores any unspecified keys rather than failing.\n\nIf you care about the details, I wrote about it on my blog: [https://ravencentri.cc/blog/dict-patterns-dont-match-dict-shapes/](https://ravencentri.cc/blog/dict-patterns-dont-match-dict-shapes/)"}
{"instruction": "Monday Daily Thread: Project ideas!", "input": "", "output": "Monday Daily Thread: Project ideas!\n# Weekly Thread: Project Ideas 💡\n\nWelcome 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.\n\n## How it Works:\n\n1. **Suggest a Project**: Comment your project idea—be it beginner-friendly or advanced.\n2. **Build & Share**: If you complete a project, reply to the original comment, share your experience, and attach your source code.\n3. **Explore**: Looking for ideas? Check out Al Sweigart's [\"The Big Book of Small Python Projects\"](https://www.amazon.com/Big-Book-Small-Python-Programming/dp/[PHONE]) for inspiration.\n\n## Guidelines:\n\n* Clearly state the difficulty level.\n* Provide a brief description and, if possible, outline the tech stack.\n* Feel free to link to tutorials or resources that might help.\n\n# Example Submissions:\n\n## Project Idea: Chatbot\n\n**Difficulty**: Intermediate\n\n**Tech Stack**: Python, NLP, Flask/FastAPI/Litestar\n\n**Description**: Create a chatbot that can answer FAQs for a website.\n\n**Resources**: [Building a Chatbot with Python](https://www.youtube.com/watch?v=a37BL0stIuM)\n\n# Project Idea: Weather Dashboard\n\n**Difficulty**: Beginner\n\n**Tech Stack**: HTML, CSS, JavaScript, API\n\n**Description**: Build a dashboard that displays real-time weather information using a weather API.\n\n**Resources**: [Weather API Tutorial](https://www.youtube.com/watch?v=9P5MY_2i7K8)\n\n## Project Idea: File Organizer\n\n**Difficulty**: Beginner\n\n**Tech Stack**: Python, File I/O\n\n**Description**: Create a script that organizes files in a directory into sub-folders based on file type.\n\n**Resources**: [Automate the Boring Stuff: Organizing Files](https://automatetheboringstuff.com/2e/chapter9/)\n\nLet's help each other grow. Happy coding! 🌟"}
{"instruction": "What can you do with Python embedded in MS Excel?", "input": "", "output": "What can you do with Python embedded in MS Excel?\nMicrosoft is supporting Python in Excel where you can put a program inside a cell. I think this feature is still a \"preview\" feature, not on the main release channel.\n\nWhat do you use it for?\n\nBecause I use external Python programs to process spreadsheets normally.\n\n1. [MS Get Started page, Python in Excel](https://support.microsoft.com/en-US/Excel/python/get-started-with-python-in-excel)"}
{"instruction": "How much time do you actually spend fixing CI failures that aren’t real bugs?", "input": "", "output": "How much time do you actually spend fixing CI failures that aren’t real bugs?\nCurious if this is just my experience or pretty common.\nIn a lot of projects I’ve touched, a big percentage of CI failures aren’t actual logic bugs. They’re things like:\ndependency updates breaking builds\nflaky tests\nlint/formatting failures\nmisconfigured GitHub Actions / CI YAML\ncaching issues\nmissing or wrong env vars\nsmall config changes that suddenly block merges\nIt often feels like a lot of time is spent just getting CI back to green rather than working on product features.\nFor people who deal with CI regularly:\nWhat kinds of CI failures eat the most time for you?\nHow often do you see failures that are basically repetitive / mechanical fixes?\nDoes CI feel like a productivity booster for you, or more like a tax?\nGenuinely curious how widespread this is."}
{"instruction": "gtasks-terminal – Google Tasks power-tool for the terminal", "input": "", "output": "gtasks-terminal – Google Tasks power-tool for the terminal\nI got tired of browser tabs just to tick off a task, so I built a zero-telemetry CLI that talks straight to the Google Tasks API.\n\nHighlights\n\n* Full CRUD + interactive picker (vim keys, fuzzy find)\n* Multi-account – personal & work at the same time\n* Auto tag extraction (`[bug]`, `[urgent]`) + duplicate killer\n* 9 built-in reports (JSON/CSV/HTML) – “what did I finish this month?”\n* External-editor support – `gtasks edit 42` opens `$EDITOR`\n* Nothing leaves your machine – OAuth tokens live in `~/.gtasks`\n\n**Install in 15 s (Python ≥ 3.7)**\n\nWindows (PowerShell):\n\n    python -m pip install gtasks-cli; python -c \"import urllib.request; exec(urllib.request.urlopen('https://raw.githubusercontent.com/sirusdas/gtasks-terminal/02689d4840bf3528f36ab26a4a129744928165ea/install.py').read())\"\n\nmacOS / Linux:\n\n    curl -sSL https://raw.githubusercontent.com/sirusdas/gtasks-terminal/02689d4840bf3528f36ab26a4a129744928165ea/install.py | python3\n\nRestart your terminal, then:\n\n    gtasks auth      # one-time browser flow\n    gtasks advanced-sync\n    gtasks interactive\n\nCode, docs, Discussions: [https://github.com/sirusdas/gtasks-terminal](https://github.com/sirusdas/gtasks-terminal)\nSome useful commands that you can use: [https://github.com/sirusdas/gtasks-terminal/blob/main/useful\\_command.md](https://github.com/sirusdas/gtasks-terminal/blob/main/useful_command.md)\nA lots of md files are present describing each operations in detail.\nPyPI: [https://pypi.org/project/gtasks-cli/](https://pypi.org/project/gtasks-cli/)\n\nIssues & PRs welcome—let me know how you use Google Tasks from the terminal!"}
{"instruction": "What actually helped you improve faster in Python: tutorials, projects, or competitions?", "input": "", "output": "What actually helped you improve faster in Python: tutorials, projects, or competitions?\nI noticed something interesting while learning. Watching tutorials made concepts feel easy, but solving problems without guidance was a completely different experience.\n\nSmall projects helped with confidence, but timed challenges and scenario-based problems exposed gaps much faster, especially around debugging, data handling, and thinking under constraints.\n\nCurious what worked best for others here:\n\n* building projects?\n* contributing to open source?\n* coding challenges?\n* or just learning on the job?\n\nWhat genuinely accelerated your Python skills the most?"}
{"instruction": "Best pattern for polling a few hundred async jobs a day without hammering an api?", "input": "", "output": "Best pattern for polling a few hundred async jobs a day without hammering an api?\nContext: We have an internal tool that pushes \\~100 videos a week through a lipsync api ([sync.so](http://sync.so)) for client work.\n\nTheir SDK is fine, you submit a generation and poll status until its done and the jobs take anywhere from 2 to 15 min.\n\nRight now i have a dumb while loop with sleep(30) per job and it obviously doesn't scale, Im either polling too often and eating 429s or too slow and jobs sit finished for minutes.\n\nThey do have webhooks but our tool runs on a box behind the company network so exposing an endpoint is a whole conversation with IT.\n\nWhats the sane middle ground here. asyncio with jittered backoff per job?"}
{"instruction": "ESPythoNOW - Send/Receive messages between Linux and ESP32/8266 devices. Now supports ESP-NOW V2.0!", "input": "", "output": "ESPythoNOW - Send/Receive messages between Linux and ESP32/8266 devices. Now supports ESP-NOW V2.0!\n* **What My Project Does**\n   * ESPythoNOW allows you send and receive ESP-NOW messages between a Linux PC and ESP32/ESP8266 micro-controllers.\n   * **It now supports ESP-NOW v2.0, allowing over 1,400 bytes per message up from the 1.0 limit of 250 bytes!**\n* **Target Audience**\n   * The target audience are project builders who wish to share data directly between Linux and ESP32/ESP8266 micro-controllers.\n* **Comparison**\n   * ESP-NOW is a protocol designed for use only between Espressif micro-controllers, to my knowledge there exists no other Python implementation of the protocol that allows data/messages to be sent and received in this way.\n\nGithub: [https://github.com/ChuckMash/ESPythoNOW](https://github.com/ChuckMash/ESPythoNOW)"}
{"instruction": "Running 60 python scripts as \"services\"", "input": "", "output": "Running 60 python scripts as \"services\"\nHi,\nI have around 60 scripts that need to run constantly, mainly event handlers and such. Right now I have an external script that launch them and monitor if the app is running on it's pid, otherwise it's relaunching the app. Works fine but get's clunky when we update some submodule and need to restart them, or to check if one crashes more than other etc..\n\nSo I would like to find a better way to approach this. It needs to run on windows and being able to access several samba shares via unc paths and being able to restart crashed scripts anf offer an easy way to restart all of them in case of an update (this part doesn't need to be automated). Every script use the same environnement\nFor now my candidates are docker, PM2 and NSSM.\nI think docker is gonna be a pain to access shares and add a lot of overhead especially on windows\nI don't know PM2 and NSSM, looks like  PM2 would be easier to setup but more JS oriented and NSSM would be harder to monitor.\n\nWhat do you think guys ?"}
{"instruction": "Spectrograms: A high-performance toolkit for audio and image analysis", "input": "", "output": "Spectrograms: A high-performance toolkit for audio and image analysis\nI’ve released [Spectrograms](https://github.com/jmg049/Spectrograms), a library designed to provide an all-in-one pipeline for spectral analysis. It was originally built to handle the spectrogram logic for my [audio_samples](https://github.com/jmg049/audio_samples) project and was abstracted into its own toolkit to provide a more complete set of features than what is currently available in the Python ecosystem.\n\n### What My Project Does\n\n**Spectrograms** provides a high-performance pipeline for computing spectrograms and performing FFT-based operations on 1D signals (audio) and 2D signals (images). It supports various frequency scales (Linear, Mel, ERB, LogHz) and amplitude scales (Power, Magnitude, Decibels), alongside general-purpose 2D FFT operations for image processing like spatial filtering and convolution.\n\n### Target Audience\n\nThis library is designed for developers and researchers requiring production-ready DSP tools. It is particularly useful for those needing batch processing efficiency, low-latency streaming support, or a Python API where metadata (like frequency/time axes) remains unified with the computation.\n\n### Comparison\n\nUnlike standard alternatives such as SciPy or Librosa which return raw `ndarrays`, **Spectrograms** returns context-aware objects that bundle metadata with the data. It uses a plan-based architecture implemented in Rust that releases the GIL, offering significant performance advantages in batch processing and parallel execution compared to naive NumPy-based implementations.\n\n---\n\n### Key Features:\n\n* **Integrated Metadata**: Results are returned as `Spectrogram` objects rather than raw `ndarrays`. This ensures the frequency and time axes are always bundled with the data. The object maintains the parameters used for its creation and provides direct access to its `duration()`, `frequencies`, and `times`. These objects can act as drop-in replacements for `ndarrays` in most scenarios since they implement the `__array__` interface.\n* **Unified API**: The library handles the full process from raw samples to scaled results. It supports `Linear`, `Mel`, `ERB`, and `LogHz` frequency scales, with amplitude scaling in `Power`, `Magnitude`, or `Decibels`. It also includes support for chromagrams, MFCCs, and general-purpose 1D and 2D FFT functions.\n* **Performance via Plan Reuse**: For batch processing, the `SpectrogramPlanner` caches FFT plans and pre-computes filterbanks to avoid re-calculating constants in a loop. **Benchmarks included in the repository show this approach to be faster across tested configurations compared to standard SciPy or Librosa implementations.** The repo includes detailed benchmarks for various configurations.\n* **GIL-free Execution**: The core compute is implemented in Rust and releases the Python Global Interpreter Lock (GIL). This allows for actual parallel processing of audio batches using standard Python threading.\n* **2D FFT Support**: The library includes support for 2D signals and spatial filtering for image processing using the same design philosophy as the audio tools.\n\n### Quick Example: Linear Spectrogram\n\n```python\nimport numpy as np\nimport spectrograms as sg\n\n# Generate a 440 Hz test signal\nsr = 16000\nt = np.linspace(0, 1.0, sr)\nsamples = np.sin(2 * np.pi * 440.0 * t)\n\n# Configure parameters\nstft = sg.StftParams(n_fft=512, hop_size=256, window=\"hanning\")\nparams = sg.SpectrogramParams(stft, sample_rate=sr)"}
{"instruction": "trueform: Real-time geometric processing for Python. NumPy in, NumPy out.", "input": "", "output": "trueform: Real-time geometric processing for Python. NumPy in, NumPy out.\n**GitHub**: [https://github.com/polydera/trueform](https://github.com/polydera/trueform)\n\n**Documentation and Examples:** [https://trueform.polydera.com/](https://trueform.polydera.com/)\n\n## What My Project Does\n\nSpatial queries, mesh booleans, isocontours, topology, at interactive speed on million-polygon meshes. Robust to non-manifold flaps and other artifacts common in production workflows.\n\nSimple code just works. Meshes cache structures on demand. Algorithms figure out what they need. NumPy arrays in, NumPy arrays out, works with your existing scipy/pandas pipelines. Spatial trees are built once and reused across transformation updates, enabling real-time interactive applications. Pre-built Blender add-on with live preview booleans included.\n\n**Live demos**: Interactive mesh booleans, cross-sections, collision detection, and more. Mesh-size selection from 50k to 500k triangles. Compiled to WASM: [https://trueform.polydera.com/live-examples/boolean](https://trueform.polydera.com/live-examples/boolean)\n\n**Building interactive applications with VTK/PyVista:** Step-by-step tutorials walk you through building real-time geometry tools: collision detection, boolean operations, intersection curves, isobands, and cross-sections. Each example is documented with the patterns for VTK integration: zero-copy conversion, transformation handling, and update loops. Drag meshes and watch results update live: [https://trueform.polydera.com/py/examples/vtk-integration](https://trueform.polydera.com/py/examples/vtk-integration)\n\n## Target Audience\n\nProduction use and research. These are Python bindings for a C++ library we've developed over years in the industry, designed to handle geometry and topology that has accumulated artifacts through long processing pipelines: non-manifold edges, inconsistent winding, degenerate faces, and other defects.\n\n## Comparison\n\nOn 1M triangles per mesh (M4 Max): 84× faster than CGAL for boolean union, 233× for intersection curves. 37× faster than libigl for self-intersection resolution. 38× faster than VTK for isocontours. Full methodology, source-code and charts: [https://trueform.polydera.com/py/benchmarks](https://trueform.polydera.com/py/benchmarks)\n\n**Getting started:** [https://trueform.polydera.com/py/getting-started](https://trueform.polydera.com/py/getting-started)\n\n**Research:** [https://trueform.polydera.com/py/about/research](https://trueform.polydera.com/py/about/research)"}
{"instruction": "Looking for Small Python Projects to Refactor", "input": "", "output": "Looking for Small Python Projects to Refactor\nI’ve been focusing heavily on Python refactoring, maintainability, and clean code practices lately, and I’m looking for a few real codebases to work on.\n\nMainly interested in projects that:\n\n* work, but became hard to maintain\n* have inconsistent structure or naming\n* grew quickly over time\n* feel difficult to extend or debug\n\nMy focus is improving:\n\n* readability\n* structure\n* maintainability\n* code clarity\n\nwhile preserving the original behavior and intent.\n\nI’m not charging for this, mainly looking for practical experience working with real projects and honest feedback on the refactors.\n\nIf you have a small-to-medium Python project that could use cleanup, feel free to DM me or share a GitHub link."}
{"instruction": "Randcraft: Object-oriented random variables", "input": "", "output": "Randcraft: Object-oriented random variables\n# RandCraft: Object-Oriented Random Variable Composition for Python\n\n## What My Project Does\n\nRandCraft is a Python library that makes it easy to combine and manipulate univariate random variables using an intuitive object-oriented interface. Built on top of scipy.stats, it allows you to add, subtract, and transform random variables from different distributions without needing to derive complex analytical solutions manually.\n\nKey features:\n- **Simple composition**: Combine random variables with `+` and `-` operators\n- **Automatic simplification**: Uses analytical solutions when possible, numerical approaches otherwise\n- **Extensive distribution support**: Normal, uniform, discrete, gamma, log-normal, and any scipy.stats continuous distribution\n- **Automatic stat calculationt** Mean, variance, moments, pdf, cdf are all calculated for you automatically\n- **Plotting** You can use `.plot()` to quickly look at any random variable\n- **Advanced features**: Kernel density estimation, mixture distributions, and custom random variable creation\n\n## Example\n\n```python\nfrom randcraft.constructors import make_normal, make_uniform, make_discrete\nfrom randcraft.misc import mix_rvs\n\nrv1 = make_normal(mean=0, std_dev=1)\n# <RandomVariable(scipy-norm): mean=0.0, var=1.0>\nrv2 = make_uniform(low=-1, high=1)\n# <RandomVariable(scipy-uniform): mean=-0.0, var=0.333>\ncombined = rv1 + rv2\n# <RandomVariable(multi): mean=0.0, var=1.33>\ndiscrete = make_discrete(values=[1, 2, 3])\n# <RandomVariable(discrete): mean=2.0, var=0.667>\n\n# Make a new rv which has a random chance of drawing from one of the other 4 rvs\nmixed = mix_rvs([rv1, rv2, combined, discrete])\n# <RandomVariable(mixture): mean=0.5, var=1.58>\nmixed.plot()\n```\n[plot output](https://github.com/RobbieKiwi/RandCraft/blob/f701111797b1904901bbf6fe9a62620327d5ebcf/images/mixture.png?raw=true)\n## Target Audience\n\nRandCraft is designed for:\n- **Data scientists and statisticians** who need to create basic combinations of independent random variables\n- **Researchers and students** studying probability theory and statistical modeling\n- **Developers** building simulation or modeling applications\n- **Anyone** who needs to combine random variables but doesn't want to derive complex analytical solutions\n\n## Comparison\n\nRandCraft differs from existing alternatives in several key ways:\n\n**vs. Direct scipy.stats usage:**\n- Provides object-oriented interface where most things you want are properties or methods on the RV object itself\n- Provides intuitive composition (e.g., `rv1 + rv2`) instead of requiring analytical approach\n\n**vs. Stan:**\n- Focused specifically on simpler uni-variate random variable composition rather than Bayesian inference\n- More accessible for users who need straightforward random variable manipulation\n\nThe library fills a niche for users who need to combine random variables frequently but want to avoid the complexity of deriving analytical solutions or writing custom simulation code.\n\n## Limitations\n\nThe library is designed to work with uni-variate random variables only. Multi-dimensional RVs or correlations etc are not supported.\n\n## Links\n\n- [PyPI](https://pypi.org/project/randcraft/)\n- [GitHub](https://github.com/RobbieKiwi/RandCraft/)\n- [Documentation](https://github.com/RobbieKiwi/RandCraft/blob/main/README.md)"}
{"instruction": "Guro – a Python library I built, and what maintaining it taught me", "input": "", "output": "Guro – a Python library I built, and what maintaining it taught me\nWhat my project does?\nguro is a Python-based system monitoring and hardware analysis toolkit that runs in the terminal. It provides real-time performance telemetry (CPU, memory, processes), thermal heatmaps, GPU diagnostics, and benchmarking tools, all accessible via a simple CLI interface.\n\nTarget audience:\nguro is aimed at Python developers, engineers, and enthusiasts who want a lightweight, terminal-centric monitoring tool built in Python. It’s designed to work across PCs, Laptops, Embedded Systems & Linux, macOS, and Windows without requiring heavy setup.\n\nComparison:\nUnlike heavyweight system monitoring GUIs or commercial tools, guro stays CLI-first, Python-based, and modular. It doesn’t try to replace full observability stacks but focuses on giving precise command-line access to system telemetry and benchmarking in a developer-friendly way. .\n\nAfter real usage and feedback (3k+ downloads), I recently released guro v1.1.3, focused on stability, bug fixes, and cleaner internals rather than new feature sprawl.\n\nRepository:\nhttps://github.com/dhanushk-offl/guro\n(Drop a star, if you find it useful)\n\nHappy to hear thoughts from others here who work with system tooling or Python-based CLI apps, especially on how you manage testing, cross-platform support, or CLI design."}
{"instruction": "I built a Python SDK that unifies OpenFDA, PubMed, and ClinicalTrials.gov", "input": "", "output": "I built a Python SDK that unifies OpenFDA, PubMed, and ClinicalTrials.gov\n# What My Project Does\n\nMedKit is a Python SDK that unifies multiple medical research APIs into a single developer-friendly interface.\n\nInstead of writing separate integrations for:\n\n* PubMed\n* OpenFDA\n* [ClinicalTrials.gov](http://ClinicalTrials.gov)\n\nMedKit provides **one consistent interface** with features like:\n\n• Natural language medical queries\n• Drug interaction detection\n• Research paper search\n• Clinical trial discovery\n• Medical relationship graphs\n\nExample:\n\n    from medkit import MedKit\n\n    with MedKit() as med:\n        results = med.ask(\"clinical trials for melanoma\")\n        print(results.trials[0].title)\n\nThe goal is to make it easier for developers, researchers, and health-tech builders to work with medical datasets without dealing with multiple APIs and inconsistent schemas.\n\nIt also includes:\n\n* sync + async support\n* disk/memory caching\n* CLI tools\n* provider plugin system\n\nExample CLI usage:\n\n    medkit papers \"CRISPR gene editing\" --limit 5 --links\n\n# Target Audience\n\nThis project is primarily intended for:\n\n• **health-tech developers** building medical apps\n• **researchers** exploring biomedical literature\n• **data scientists** working with medical datasets\n• **hackathon / prototype builders** in healthcare\n\nRight now it's **early stage but production-oriented** and designed to be extended with additional providers.\n\n# Comparison\n\nThere are Python libraries for **individual medical APIs**, but most developers still need to integrate them manually.\n\nExamples:\n\n|Tool|Limitation|\n|:-|:-|\n|PubMed API wrappers|Only covers research papers|\n|OpenFDA wrappers|Only covers FDA drug data|\n|ClinicalTrials API|Only covers trials|\n\nMedKit focuses on **unifying these sources under a single interface** while adding higher-level features like:\n\n• unified schema\n• natural language queries\n• knowledge graph relationships\n• interaction detection\n\n# Example Output\n\nSearching for insulin currently returns:\n\n    === Found Drugs ===\n    Drug: ADMELOG (INSULIN LISPRO)\n\n    === Research Papers ===\n    1. Practical Approaches to Insulin Pump Troubleshooting for Inpatient Nurses\n    2. Antibiotic consumption and medication cost in diabetic patients\n    3. Once-weekly Lonapegsomatropin Phase 3 Trial\n\n# Source Code\n\nGitHub:\n[https://github.com/interestng/medkit](https://github.com/interestng/medkit)\n\nPyPI:\n[https://pypi.org/project/medkit-sdk/](https://pypi.org/project/medkit-sdk/)\n\nInstall:\n\n    pip install medkit-sdk\n\n# Feedback\n\nI'd love feedback from Python developers, health-tech engineers, or researchers on:\n\n• API design\n• additional providers to support\n• features that would make this useful in real workflows"}
{"instruction": "Built a tool that verifies COBOL-to-Python translations", "input": "", "output": "Built a tool that verifies COBOL-to-Python translations\nHey everyone. I'm a high school student and I've been working on a tool called Aletheia for the past month.\n\nThe idea: banks are scared to touch their COBOL because generic AI translates syntax but breaks the financial math — stuff like truncation vs rounding, decimal precision, calculation order.\n\nMy tool analyzes COBOL, extracts the exact logic, and generates Python that's verified to behave the same way.\n\nI'm not trying to sell anything. I just want to know from people who actually work with this stuff:\n\n* Does this solve a real problem you've seen?\n* What would make something like this actually useful?\n* Am I missing something obvious?\n\nHappy to show a demo if anyone's curious."}
{"instruction": "Security holes I keep finding in AI-generated Python", "input": "", "output": "Security holes I keep finding in AI-generated Python\nI've been using Claude Code and Cursor for most of my backend work this year, and at some point I started keeping a tally of what I catch in review. Out of our last 40 agent PRs, 14 had at least one of these:\n\n\\- SQL queries built with f-strings instead of parameters\n\n\\- subprocess calls with shell=True taking user-shaped input\n\n\\- yaml.load on config that comes from outside, which is still unsafe by default\n\n\\- API keys pasted straight into the source instead of env vars\n\n\\- except Exception: pass around auth code, so failures just disappear\n\nThe annoying part is that all of it runs. Tests pass, the happy path works, the diff looks clean. The shell=True one made it through two human reviews before I caught it on a random Friday reread.\n\nWe run bandit in CI and Coderabbit on the PRs. Between them they flagged the SQL one and the hardcoded keys, but the yaml and the except/pass went through quietly, so I still end up reading everything myself.\n\nMaybe my prompting is bad, I accept that. But 14 out of 40 feels less like a prompting problem and more like a pattern"}
{"instruction": "I built reru: A drop-in replacement for the standard 're' module (written in Rust). Up to 40x faster", "input": "", "output": "I built reru: A drop-in replacement for the standard 're' module (written in Rust). Up to 40x faster\nHey r/Python!\n\nI wanted to share an open-source project I’ve been working on to push regex performance to its limits.\n\n# What My Project Does\n\n`reru` is a high-performance, drop-in replacement for Python's standard `re` module, built using Rust and PyO3.\n\nThe speed comes from a dynamic, 4-stage hybrid architecture that parses your regex pattern and automatically routes it to the optimal backend:\n\n1. **Literal Scan:** Uses raw memory scanning (`memchr`) for pure string searches.\n2. **Rust** `regex`**:** Uses linear-time matching to guarantee protection against ReDoS for standard patterns.\n3. `pcre2` **(JIT):** Automatically takes over for patterns containing heavy wildcards (`.*`), lookarounds, or backreferences.\n4. `fancy-regex`**:** The final fallback safety net to ensure maximum compatibility with Python's unique syntax quirks.\n\n# Target Audience\n\nThis library is intended for developers dealing with massive text payloads—like log parsing, heavy web scraping, or data cleaning (ETL) pipelines—where standard regex becomes a processing bottleneck.\n\nIt is currently in Beta, but to ensure it is actually a reliable \"drop-in\" replacement, I ported the official Python standard library `re` test suite into the project to rigorously map out, fix, and document behavioral differences. It supports standard methods like `match`, `search`, `findall`, and `sub`, plus named capture groups.\n\n# Comparison\n\nCompared to the standard `re` module (which is C-based and relies on a standard backtracking engine), `reru` scales significantly better on large inputs thanks to its algorithmic engine routing.\n\nIn my benchmarks (10,000 iterations on a 13,000+ character padded string), `reru` completely leaves the standard library behind:\n\n* Alternation `(Python|Perl|Tcl)` ➔ **\\~39x faster** (routed to Rust regex).\n* Literal search `.*Python.*` ➔ **\\~34x faster** (routed to memchr).\n* Backreferences `(Python)\\1` ➔ **\\~8x faster** (routed to pcre2).\n\n*(Note: On very small strings, FFI overhead makes it comparable to* `re`*, but it shines as inputs grow).*\n\n*benchmarks:* [*https://github.com/berrytern/reru/tree/master/benchmarks*](https://github.com/berrytern/reru/tree/master/benchmarks)\n\n# Try it out\n\nYou can install it directly via pip: `pip install reru`\n\n**GitHub Repo:**[https://github.com/berrytern/reru](https://github.com/berrytern/reru)\n\nI'd love to get some feedback from this community! If you deal with massive text payloads, give it a spin and let me know how it performs."}
{"instruction": "I built Embex: A Universal Vector Database ORM with a Rust core for 2-3x faster vector operations", "input": "", "output": "I built Embex: A Universal Vector Database ORM with a Rust core for 2-3x faster vector operations\n**What My Project Does**\n\nEmbex is a universal ORM for vector databases. It provides a unified Python API to interact with multiple vector store providers (currently Qdrant, Pinecone, Chroma, LanceDB, Milvus, Weaviate, and PgVector).\n\nUnder the hood, it is not just a Python wrapper. I implemented the core logic in **Rust** using the \"BridgeRust\" framework I developed. This Rust core is compiled into a Python extension module using **PyO3**.\n\nThis architecture allows Embex to perform heavy vector math operations (like cosine similarity and dot products) using SIMD intrinsics (AVX2/NEON) directly in the Rust layer, which are then exposed to Python. This results in vector operations that are roughly **4x faster** than standard scalar implementations, while keeping the Python API idiomatic and simple.\n\n**Target Audience**\n\nThis library is designed for:\n\n* **AI/ML Engineers** building RAG (Retrieval-Augmented Generation) pipelines who want to switch between vector databases (e.g., local LanceDB/Chroma for dev, Pinecone for prod) without rewriting their data access layer.\n* **Backend Developers** who need a consistent interface for vector storage that doesn't lock them into a single vendor's SDK.\n* **Performance enthusiasts** looking for Python tools that leverage Rust for low-level optimization.\n\n**Comparison**\n\n* **vs. Native SDKs (e.g.,** `pinecone-client`**,** `qdrant-client`**):** Native SDKs are tightly coupled to their specific backend. If you start with one and want to migrate to another, you have to rewrite your query logic. Embex abstracts this; you change the provider configuration, and your `search` or `insert` code remains exactly the same.\n* **vs. LangChain VectorStores:** LangChain is a massive framework where the vector store is just one small part of a huge ecosystem. Embex is a standalone, lightweight ORM focused solely on the database layer. It is less opinionated about your overall application architecture and significantly lighter to install if you don't need the rest of LangChain.\n* **Performance:** Because the vector operations happen in the compiled Rust core using SIMD instructions, Embex benchmarks at 3.6x - 4.0x faster for mathematical vector operations compared to pure Python or non-SIMD implementations.\n\n**Links & Source**\n\n* **GitHub:**[https://github.com/bridgerust/bridgerust](https://github.com/bridgerust/bridgerust)\n* **PyPI:** `pip install embex`\n* **Docs:**[https://bridgerust.dev/embex/introduction](https://bridgerust.dev/embex/introduction)\n\nI would love feedback on the API design or the PyO3 bindings implementation!"}
{"instruction": "SNKV – I built a key-value store for Python that skips SQLite's SQL layer entirely", "input": "", "output": "SNKV – I built a key-value store for Python that skips SQLite's SQL layer entirely\n**What My Project Does**\n\n[SNKV ](https://github.com/hash-anu/snkv)is a free, open-source embedded key-value store. It uses SQLite's B-Tree engine for storage but removes the SQL layer entirely — no parser, no query planner, no statement prep. Just a plain dict-style API:\n\n    from snkv import KVStore\n\n    with KVStore(\"mydb.db\") as db:\n        db[\"hello\"] = \"world\"\n        print(db[\"hello\"])       # b\"world\"\n        print(db.get(\"missing\")) # None\n\nIt also supports ACID transactions, WAL mode, prefix iteration, column families, and incremental vacuum.\n\nInstall: `pip install snkv`\n\n**Target Audience**\n\nEarly adopters and people who want to try it out. Aimed at CLI tools, desktop apps, local caches, and edge/IoT use cases where you want an embedded KV store without writing SQL. Crash safety has been validated with a 10 GB kill-9 stress test. API may still change before 1.0.\n\n**Comparison**\n\nThe closest alternatives are sqlite3 (stdlib), lmdb, and rocksdb.\n\nVersus sqlite3: same underlying storage engine, but without the SQL overhead. Random reads are \\~1.6x faster and sequential scans \\~2x faster on KV workloads. If you're already using SQL in your app, just stick with sqlite3. If you only need key-value access, SNKV is less boilerplate and faster.\n\nVersus lmdb: lmdb is faster when the entire dataset fits in RAM (memory-mapped). SNKV has more predictable memory use and installs with a single pip command without needing a system library.\n\nVersus rocksdb: rocksdb wins on write-heavy workloads (LSM-tree). It's also notoriously painful to install on Python. SNKV is simpler and has no compaction stalls."}
{"instruction": "Mark lutz or Eric lutz?", "input": "", "output": "Mark lutz or Eric lutz?\nhey 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\n\n 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."}
{"instruction": "unwrappy: Rust-inspired Result and Option types with lazy async chaining for Python", "input": "", "output": "unwrappy: Rust-inspired Result and Option types with lazy async chaining for Python\nI built a library that brings Rust's `Result` and `Option` types to Python, with lazy evaluation for clean async operation chaining (inspired by Polars' deferred execution).\n\n### What My Project Does\n\n**unwrappy** provides:\n\n- **Result[T, E]** - Success (`Ok`) or failure (`Err`) - errors as values, not exceptions\n- **Option[T]** - Presence (`Some`) or absence (`Nothing`) - explicit optionality\n- **LazyResult / LazyOption** - Build async pipelines without nested awaits\n\n```python\nfrom unwrappy import Ok, Err, Some, NOTHING, LazyResult\n\n# Pattern matching (Python 3.10+)\nmatch divide(10, 0):\n    case Ok(value):\n        print(f\"Result: {value}\")\n    case Err(error):\n        print(f\"Error: {error}\")\n\n# Option for nullable values\nemail = from_nullable(get_user_email(42))  # Some(\"...\") or NOTHING\ndisplay = email.map(lambda e: e.split(\"@\")[0]).unwrap_or(\"Anonymous\")\n\n# Lazy async chaining - no nested awaits\nresult = await (\n    LazyResult.from_awaitable(fetch_user(42))\n    .and_then(fetch_profile)\n    .map(lambda p: p[\"name\"].upper())\n    .collect()\n)\n```\n\nFull combinator API: `map`, `and_then`, `or_else`, `filter`, `zip`, `flatten`, `tee`, and more.\n\n### Target Audience\n\n**Production-ready** - 99% test coverage, fully typed, zero dependencies. Best for API boundaries and data pipelines where you want explicit error handling.\n\n### Why This Exists\n\nThe `rustedpy` ecosystem (`result`, `option`) is no longer actively maintained. I needed a maintained alternative with proper async support, so I built unwrappy with `LazyResult`/`LazyOption` for clean async pipeline composition.\n\n**Links:**\n- GitHub: https://github.com/leodiegues/unwrappy\n- PyPI: `pip install unwrappy`\n- Docs: https://leodiegues.github.io/unwrappy\n\nFeedbacks and contributions are welcome!"}
{"instruction": "Ludic 1.0.0 supports safe HTML rendering with t-strings", "input": "", "output": "Ludic 1.0.0 supports safe HTML rendering with t-strings\nHi, I've recently released a feature in Ludic which allows rendering HTML with t-strings.\n\n### What My Project Does\n\nLudic allows HTML generation in Python while utilizing Python's typing system. The goal is to enable the creation of dynamic web applications with reusable components, all while offering a greater level of type safety than raw HTML.\n\n#### Example\n\n```\nfrom ludic.web import LudicApp\nfrom ludic.html import b, p\n\nfrom .components import Link\n\napp = LudicApp()\n\n@app.get(\"/\")\nasync def homepage() -> p:\n    return p(t\"Hello {b(\"Stranger\")}! Click {Link(\"here\", to=\"https://example.com\")}!\")\n```\n\n#### t-strings\n\nUsing t-strings makes longer blocks of text more readable. Here is an example:\n\n```\np(\n    t\"\"\"\n    Here is a long {i(\"paragraph\")} that would otherwise be very\n    hard to read. Using t-strings (which are optional),\n    it can {b(\"improve readability\")} a lot.\n    {br()}\n    {br()}\n\n    It is also possible to use nested t-string with variables.\n    Here is an example:\n\n    {div(*(span(number) for number in range(10)))}\n    \"\"\"\n)\n```\n\n### Target Audience\n\nPython developers who want to build server-rendered web pages without heavy full-stack frameworks.\n\n### Links\n\n- [GitHub](https://github.com/getludic/ludic)"}
{"instruction": "I wrote an opensource SEC filing compliance package", "input": "", "output": "I wrote an opensource SEC filing compliance package\nThe U.S. Securities and Exchange Commission requires companies and individuals to submit data in SEC specific formats. Usually this means taking a columnar dataset and converting it to a specific XML schema.\n\nIn practice, this usually means paying a company for proprietary filing software that is annoying to use, and is not modifiable.\n\n# What My Project Does\n\nMaps data in columnar format to the XML schema the SEC expects. Has a parser for every XML file type.\n\n    from secfiler import construct_document\n\n    rows = [\n      {\"footnoteText\": \"Contributions to non-profit organizations.\", \"footnoteId\": \"F1\", \"_table\": \"345_footnote\"},\n      {\"aff10B5One\": \"0\", \"documentType\": \"4\", \"notSubjectToSection16\": \"0\", \"periodOfReport\": \"[PHONE]\", \"remarks\": None, \"schemaVersion\": \"X0508\", \"issuerCik\": \"[PHONE]\", \"issuerName\": \"AMAZON COM INC\", \"issuerTradingSymbol\": \"AMZN\", \"_table\": \"345\"},\n      {\"signatureDate\": \"[PHONE]\", \"signatureName\": \"/s/ PAUL DAUBER, attorney-in-fact for Jeffrey P. Bezos, Executive Chair\", \"_table\": \"345_owner_signature\"},\n      {\"rptOwnerCity\": \"SEATTLE\", \"rptOwnerState\": \"WA\", \"rptOwnerStateDescription\": None, \"rptOwnerStreet1\": \"P.O. BOX 81226\", \"rptOwnerStreet2\": None, \"rptOwnerZipCode\": \"[PHONE]\", \"rptOwnerCik\": \"[PHONE]\", \"rptOwnerName\": \"BEZOS JEFFREY P\", \"isDirector\": \"1\", \"isOfficer\": \"1\", \"isOther\": \"0\", \"isTenPercentOwner\": \"0\", \"officerTitle\": \"Executive Chair\", \"_table\": \"345_reporting_owner\"},\n      {\"securityTitleValue\": \"Common Stock, par value $.01  per share\", \"equitySwapInvolved\": \"0\", \"transactionCode\": \"G\", \"transactionFormType\": \"4\", \"transactionDateValue\": \"[PHONE]\", \"directOrIndirectOwnershipValue\": \"D\", \"sharesOwnedFollowingTransactionValue\": \"883258188\", \"transactionAcquiredDisposedCodeValue\": \"D\", \"transactionPricePerShareValue\": \"0\", \"transactionSharesValue\": \"421693\", \"transactionCodingFootnoteIdId\": \"F1\", \"_table\": \"345_non_derivative_transaction\"},\n    ]\n\n    xml_bytes = construct_document(rows, '4')\n    with open('bezosform4.xml', 'wb') as f:\n                f.write(xml_bytes)\n\n# Target Audience\n\n* This package is not intended to be used by companies actually filing for the SEC. It was suggested by a compliance officer at a trading firm who was annoyed by using irritating software he could not modify.\n* It is intended as a mostly correct open source example for startups, companies, PhD students, etc to build something better off of.\n* I've left a watermark in the package, and will cringe if I see it appear in future SEC filings.\n\n# Comparison\n\nI am not aware of any open source SEC filing software.\n\n# GitHub\n\n[https://github.com/john-friedman/secfiler](https://github.com/john-friedman/secfiler)\n\n# Skirting the boundaries of taste\n\nI generally do not like vibecoded projects. I think they make this subreddit worse. This package is largely vibecoded, but I think it is worth posting.\n\nThat is because the hard part of this package was:\n\n1. Calculating the xpath of every SEC xml file (6tb, millions of files). This required having an archive of every SEC filing, and deploying ec2 instances. [Original mappings here.](https://github.com/john-friedman/Reverse-Engineering-Columnar-Mappings-of-all-SEC-XML-Files/tree/master/data)\n2. Validating outputs using my very much not vibe coded package for sec filings: [datamule](https://github.com/john-friedman/datamule-python).\n\nThis project was a sidequest. I needed the mappings fr"}
{"instruction": "Apache Fory Serialization 1.0.0 Released Now", "input": "", "output": "Apache Fory Serialization 1.0.0 Released Now\nKey Features:\n\n* Unified xlang type system and xlang is default serialization mode now across java/python/c++/rust/go/c#/swift/javascript/dart/kotlin/scala.\n* Decimal, bfloat16, dense array support for xlang serialization.\n* Android serialization and Java annotation processor support\n* Kotlin xlang, KSP, and schema IDL support\n* Scala schema IDL support and scala3 macro derived serializer\n* Serialization performance improvements"}
{"instruction": "SQLAlchemy, but everything is a DataFrame now", "input": "", "output": "SQLAlchemy, but everything is a DataFrame now\n**What My Project Does:**\n\nI built a DataFrame-style query engine on top of SQLAlchemy that lets you write SQL queries using the same patterns you’d use in **PySpark, Pandas, or Polars**. Instead of writing raw SQL or ORM-style code, you compose queries using a familiar DataFrame interface, and Moltres translates that into SQL via SQLAlchemy.\n\n**Target Audience:**\n\nData Scientists, Data Analysts, and Backend Developers who are comfortable working with DataFrames and want a more expressive, composable way to build SQL queries.\n\n**Comparison:**\n\nWorks like SQLAlchemy, but with a **DataFrame-first API** — think writing Spark/Polars-style transformations that compile down to SQL.\n\nDocs:\n\n[https://moltres.readthedocs.io/en/latest/index.html](https://moltres.readthedocs.io/en/latest/index.html)\n\nRepo:\n\n[https://github.com/eddiethedean/moltres](https://github.com/eddiethedean/moltres)"}
{"instruction": "Dumb Justice: building a free federal bankruptcy court scanner out of Python and RSS feeds", "input": "", "output": "Dumb Justice: building a free federal bankruptcy court scanner out of Python and RSS feeds\n\\## What My Project Does\n\nA couple days ago I posted here about a stdlib-only tool that screens bankruptcy court data for cases where people paid lawyers for something arithmetically impossible. Three dates, one subtraction, hundreds of hits. Some of you ran it, some of you had questions. This is the other half of the project.\n\nEvery US bankruptcy court publishes a free RSS feed with every new docket entry. About 90 courts, all with the same URL pattern. The feeds roll every 24 hours or so, and if you miss it, it's gone. So I wrote a poller that grabs the XML, deduplicates by GUID, stores everything in SQLite, and runs a few layers of checks on each entry. Daily operating cost: $0.\n\nThe layer my wife was reacting to when she named it is the dumbest one. When a new Chapter 13 filing hits the feed, the system fuzzy-matches the debtor's name against every prior filing in the database. If that person already got a discharge recently, federal law says they can't get another one. Same three-date subtraction from the first tool, but now it runs automatically on every new filing as it appears. No human in the loop. Just \\`datetime\\` doing \\`datetime\\` things.\n\nShe watched me explain this and said \"so it's just... dumb justice?\" And yeah. It is. The justice is in the dumbness. No AI, no ML, no inference, no ambiguity. The dates either work or they don't.\n\nThe fuzzy matching was the genuinely hard part. PACER names are chaotic. Suffixes (Jr., III, Sr.), \"NMN\" placeholders for no middle name, random casing, and joint filings like \"John Smith and Jane Smith\" that need to be split so each spouse gets matched independently. The first version was pure stdlib: strip suffixes, normalize to lowercase, match on first + last tokens. It worked, but it struggled with misspellings and abbreviations in the docket text itself. \"Mtn to Dsmss\" doesn't fuzzy-match well against \"Motion to Dismiss.\"\n\nAfter the first post, one of you suggested looking into embeddings for the text classification side. So I added a vector search layer using \\`sentence-transformers\\` (all-MiniLM-L6-v2, 384 dimensions, runs locally). It lazy-loads the model only when needed, caches embeddings to disk as numpy arrays, and falls back to regex when the model isn't available. The name matching is still the original stdlib approach (that's a structured data problem, not a semantic one), but classifying what a docket entry \\*means\\* (\"is this a dismissal or just a dismissal hearing notice?\") got dramatically better with embeddings. Hybrid approach: vector primary, regex fallback. One real dependency, but it earned its spot.\n\nThe rest of the stack is deliberately boring:\n\n\\- \\`xml.etree.ElementTree\\` parses the RSS\n\n\\- \\`urllib.request\\` fetches with retry logic (courts 503 occasionally)\n\n\\- \\`sqlite3\\` in WAL mode stores everything permanently\n\n\\- \\`csv\\` ingests the bulk data exports\n\n\\- \\`email.utils.parsedate\\_to\\_datetime\\` handles RFC 2822 dates without any manual parsing (this one saved me real pain)\n\n\\- \\`collections.Counter\\` and \\`defaultdict(list)\\` for real-time aggregation\n\nOne pip install (\\`sentence-transformers\\`) for the vector layer. Everything else is stdlib. About 1,300 lines across three core scripts and a batch file that runs on Task Scheduler. SQLite database is around 15MB after months of accumulation.\n\nThe one gotcha that actually got me: case numbers aren't unique across courts."}
{"instruction": "Looked back at code I wrote years ago — cleaned it up into a lazy, zero-dep dataframe library", "input": "", "output": "Looked back at code I wrote years ago — cleaned it up into a lazy, zero-dep dataframe library\nHi r/Python,\n\n**What My Project Does**\n\n[**pyfloe**](https://github.com/Edwardvaneechoud/pyfloe) is a lazy, expression-based dataframe library in pure Python. Zero dependencies. It builds a query plan instead of executing immediately, runs it through an optimizer (filter pushdown, column pruning), and executes using the volcano/iterator model. Supports joins (hash + sort-merge), window functions, streaming I/O, type safety, and CSV type inference.\n\n    import pyfloe as pf\n\n    result = (\n        pf.read_csv(\"orders.csv\")\n        .filter(pf.col(\"amount\") > 100)\n        .with_column(\"rank\", pf.row_number()\n            .over(partition_by=\"region\", order_by=\"amount\"))\n        .select(\"order_id\", \"region\", \"amount\", \"rank\")\n        .sort(\"region\", \"rank\")\n    )\n\n**Target Audience**\n\nPrimarily a learning tool — not a production replacement for Pandas or Polars. Also practical where zero dependencies matter: Lambdas, CLI tools, embedded ETL.\n\n**Comparison**\n\nUnlike Pandas, pyfloe is lazy — nothing runs until you trigger it, which enables optimization. Unlike Polars, it's pure Python — much slower on large datasets, but zero install overhead and a fully readable codebase. The API is similar to Polars/PySpark.\n\n**Some of the fun implementation details:**\n\n* **Volcano/iterator execution model** — same as PostgreSQL. Each plan node is a generator that pulls rows from its child. For streaming pipelines (`read_csv → filter → to_csv`), exactly one row is in memory at a time\n* **Expressions are ASTs, not lambdas** — `pf.col(\"amount\") > 100` returns a `BinaryExpr` object, not a boolean. This is what makes optimization possible — the engine can inspect expressions to decide which side of a join a filter belongs to\n* **Rows are tuples, not dicts** — \\~40% less memory. Column-to-index mapping lives in the schema; conversion to dicts happens only at the output boundary\n* **Two-phase CSV type inference** — a type ladder (`bool → int → float → str`) on a sample, then a separate datetime detection pass that caches the format string for streaming\n* **Sort-merge joins and sorted aggregation** — when your data is pre-sorted, both joins and group-bys run in O(1) memory\n\n**Why build this?** It originally started as the engine behind Flowfile. That eventually moved to Polars, but when I looked at the code a while ago, it was fun to read back code from before AI and I thought it deserved a cleanup and pushed it as a package.\n\nI also turned it into a free course: [Build Your Own DataFrame](https://edwardvaneechoud.github.io/pyfloe-tutorial/introduction/) — 5 modules that walk you through building each layer yourself, with interactive code blocks you can run in the browser.\n\nTo be clear — pyfloe is not trying to compete with Pandas or Polars on performance. But if you've ever been curious what's actually going on when you call `.filter()` or `.join()`, this might be a good place to look :)\n\n`pip install pyfloe`\n\n* Docs: [https://edwardvaneechoud.github.io/pyfloe/](https://edwardvaneechoud.github.io/pyfloe/)\n* Source: [https://github.com/Edwardvaneechoud/pyfloe](https://github.com/Edwardvaneechoud/pyfloe)\n* Course: [https://edwardvaneechoud.github.io/pyfloe-tutorial/introduction/](https://edwardvaneechoud.github.io/pyfloe-tutorial/introduction/)"}
{"instruction": "Blog: Choosing a Type Checker for Positron (Python/R Data Science IDE)", "input": "", "output": "Blog: Choosing a Type Checker for Positron (Python/R Data Science IDE)\nThe open-source Python type checker and language server ecosystem has exploded. Over the past couple years, four language server extensions have appeared, each with a different take on what Python type checking should look like.\n\nThe Positron team evaluated  to decide which one to bundle with [Positron](https://positron.posit.co/) to enhance the Python data science experience.\n\nThey compared Pyrefly, basedpyright, ty, and zuban along the following dimensions:\n- Feature completeness\n- Correctness\n- Performance\n- Ecosystem\n\nRead the full blog to see what they chose and why: https://positron.posit.co/blog/posts/[PHONE]-python-type-checkers/"}
{"instruction": "Pyxel for game development", "input": "", "output": "Pyxel for game development\nJust to say that I started developing a Survivors game with my son using Pyxel and Python (and a little bit of Pygame-ce for the music) and I really like it!! Anyone else having fun with Pyxel?"}
{"instruction": "New online Python IDE: Strype", "input": "", "output": "New online Python IDE: Strype\n\nThere is a new(-ish) online Python IDE out: [Strype](https://strype.org)\n\nNo account necessary – just start programming.\n\nIt can create graphics and animated games really easily. There are [some tutorial videos](https://www.youtube.com/@strype-programming) (see especially [this one here](https://www.youtube.com/watch?v=U4CwB8fTTZs)), and there is a [full textbook available](https://strype.org/book) (the first chapter gives a good intro to programming with Strype and graphics)."}
{"instruction": "I wrote a Matplotlib scale that collapses weekends and off-hours on datetime x-axis", "input": "", "output": "I wrote a Matplotlib scale that collapses weekends and off-hours on datetime x-axis\nFinancial time-series plots in Matplotlib have weekend gaps when plotted with datetime on the x-axis. A common workaround is to plot against an integer index instead of datetimes, but that breaks Matplotlib’s date formatting, locators, and other datetime-aware tools.\n\nA while ago I came up with a solution and wrote a custom Matplotlib scale that removes those gaps while keeping a proper datetime axis. I have now put it into a Python package:\n\n# What my project does\n\nImplements and ships a Matplotlib scale to remove weekends, holidays, and off-hours from datetime x-axes.\n\nUnder the hood, Matplotlib represents datetimes as *days since [PHONE]*. This scale remaps the values to *business days since [PHONE]*, skipping weekends, holidays, and off-hours. Business days are configurable using the standard \\`numpy.is\\_busday\\` options.  Conceptually, it behaves like a log scale: a transform applied to the axis rather than to the data itself.\n\n# Target audience\n\nAnyone plotting financial or business time-series data that wants to remove non-business time from the x-axis.\n\n# Usage\n\n    pip install busdayaxis\n\n\n    import busdayaxis\n    busdayaxis.register_scale()   # register the scale with Matplotlib\n\n\n    ax.set_xscale(\"busday\") # removes weekends\n    ax.set_xscale(\"busday\", bushours=(9, 17)) # also collapses overnight gaps\n\n**GitHub** with example: [https://github.com/saemeon/busdayaxis](https://github.com/saemeon/busdayaxis)\n\n**Docs** with multiple examples: [https://saemeon.github.io/busdayaxis/](https://saemeon.github.io/busdayaxis/)\n\nThis is my first published Python package and also my first proper Reddit post. Feedback, comments, suggestions, or criticism are very welcome."}
{"instruction": "Please recommend a front-end framework/package", "input": "", "output": "Please recommend a front-end framework/package\nI'm building an app with streamlit.\n> Why streamlit?\n\nBecause I have no frontend experience and streamlit helped me get off the ground pretty quickly. Also, I'm simultaneously deploying to web and desktop,  and streamlit lets me do this with just the one codebase (I intend to use something like PyInstaller for distribution)\n\nI have different \"[expanders](https://docs.streamlit.io/develop/api-reference/layout/st.expander)\" in my streamlit application. Each expander has some data/input elements in it (in the case of my most recent problem, it's a `data_editor`). Sometimes, I need one element to update in response to the user clicking on \"Save Changes\" in a different part of the application. If they were both in the same fragment, I could just do `st.rerun(scope='fragment')`. But since they're not, I have no other choice but to do `st.rerun()`. But if there's incorrect input, I write an error message, which gets subsequently erased due to the rerun. Now I know that I can store this stuff in `st.session_state` and add additional logic to \"recreate\" the (prior) error-message state of the app, but that adds a lot of complexity.\n\nSince there is no way to `st.rerun()` a different fragment than the one I'm in, it looks like I have to give up streamlit - about time, I've been writing workarounds/hacks for a lot of streamlit stumbling blocks.\n\nSo, would anyone be able to recommend an alternative to streamlit? These are the criteria to determine viability of an alternative:\n\n1. ability to control the layout of my elements and programmatically refresh specific elements on demand\n1. web and desktop deployments from the same codebase\n  1. bonus points for being able to handle mobile deployments as well\n1. Python API - I can learn another language if the learning curve is fast. That takes Node/React out of the realm of possibility\n1. somewhat mature - I started using streamlit back in v0.35 or so. But now I'm using v1.52. While streamlit hasn't been around for as long as React, v1.52 is sufficiently mature. I doubt a flashy new frontend framework (eg: with current version 0.43) would have had enough time to iron out the bugs if it's only been around for a very short period of time (eg: 6 months).\n1. ideally something you have experience with and can therefore speak confidently to its stability/reliability\n\nI'm currently considering:\n1. [flet](https://flet.dev/): hasn't been around for very long - anyone know if it's any good?\n1. [NiceGUI](https://nicegui.io)\n1. [Reflex](https://github.com/reflex-dev/reflex)\n\nIf anyone has any thoughts or suggestions, I'd love them\n\nThank you"}
{"instruction": "Do we really check library security?", "input": "", "output": "Do we really check library security?\nPyPi's filtering isn't cutting it. We all know it. I know the people about to say to just use the popular libraries that have community moderation.\n\nThe recent claude code injection hack in Torch has proved that isn't a solution.\n\nhttps://www.reddit.com/r/Python/s/2lwDYSv0eT\n\nAnd scanning packages are either unmaintained or maintained by one dev in the middle of nowhere.\n\nhttps://pypi.org/project/safety/\n\nSo, I honestly ask you, short of reading each libraries code by hand or avoiding them entirely how do you stay safe?\n\nSandbox enviroments? Winging it? Hope?"}
{"instruction": "Computing the close encounter between Apophis and Earth in 2029 (tutorial)", "input": "", "output": "Computing the close encounter between Apophis and Earth in 2029 (tutorial)\nHey everyone and all space enthusiasts,\n\n\nOn April 13, 2029, the asteroid **99942 Apophis** will fly past Earth at roughly 38,000 km. Closer than our geostationary satellites! Its discovery history was pretty interesting, because in the beginning there was a 2.7 % chance of an impact (don't worry, it is almost null now). So I decided to use NASA/JPL's SPICE toolkit using Python (`spiceypy`) to calculate the encounter's properties.\n\n\nI documented the entire project in a Jupyter Notebook and put together a complete video walk-through tutorial. Code: [https://github.com/ThomasAlbin/Space-Science-With-Python/blob/main/2026/04\\_SPICE\\_Apohis\\_2029\\_Flyby.ipynb](https://github.com/ThomasAlbin/Space-Science-With-Python/blob/main/2026/04_SPICE_Apohis_2029_Flyby.ipynb)\n\nVideo: [https://www.youtube.com/watch?v=j4mJTR-BTto](https://www.youtube.com/watch?v=j4mJTR-BTto)\n\nWhat the tutorial does (and why it's 30 minutes long 😅):\n\n* Computing the time when Apophis enters Earth's gravitational vicinity (the Sphere of Influece)\n* Computing the closest appraoch (distance and time)\n* Computing how the orbital elements (the dynamical properties to describe orbits in space) change after the encounter with Earth.\n\nBy the way: I used also Python + NASA's Cosmographia to create a nice 3D animation of the encounter :). But I will post it soon on my YouTube channel. Since the corresponding code is a complete mess I won't post it here, because I will only post the animation. I have to clean it up...\n\n\nBest,\n\nThomas (your Cassini/Huygens scientist)"}
{"instruction": "I built a 3D Acoustic Camera using Python (OpenCV + NumPy) and a Raspberry Pi with DMA timing", "input": "", "output": "I built a 3D Acoustic Camera using Python (OpenCV + NumPy) and a Raspberry Pi with DMA timing\n**Project:**\nI wanted to visualize 40kHz ultrasonic sound waves in 3D. Standard cameras can only capture a 2D \"shadow\" (Schlieren photography), so I built a rig to slice the sound wave at different time instances and reconstruct it.\n\n**Python Stack:**\n\n* **Hardware Control:** I used a Raspberry Pi 4. The biggest challenge was the standard Linux jitter on the GPIO pins. I used the pigpio library to access **DMA (Direct Memory Access)**, allowing me to generate microsecond-precise triggers for the ultrasonic transducer and the LED strobe without CPU interference.\n* **Image Processing:** I used **OpenCV** for background subtraction (to remove air currents from the room).\n* **Reconstruction:** I used **NumPy** to normalize the pixel brightness values and convert them into a Z-height displacement map, essentially turning brightness into topography.\n* **Visualization:** The final 3D meshes were plotted using **Matplotlib** (mplot3d).\n\n**Result (Video):**\nHere is the video showing the Python script in action and the final 3D render:\n[**https://www.youtube.com/watch?v=7qHqst\\_3yb0**](https://www.youtube.com/watch?v=7qHqst_3yb0)\n\n**Source Code:**\nAll the code for the 3D reconstruction is here:\n[https://github.com/Plasmatronixrepo/3D\\_Schlieren](https://github.com/Plasmatronixrepo/3D_Schlieren)\n\nand the 2D version:\n[https://github.com/Plasmatronixrepo/Schlieren\\_rig](https://github.com/Plasmatronixrepo/Schlieren_rig)"}
{"instruction": "sharepoint-to-text: Pure Python text extraction for Office (doc/docx/xls/xlsx/ppt/pptx), PDF, mails", "input": "", "output": "sharepoint-to-text: Pure Python text extraction for Office (doc/docx/xls/xlsx/ppt/pptx), PDF, mails\n**What My Project Does**\n\n`sharepoint-to-text` is a pure Python library that extracts text, metadata, and structured content (pages, slides, sheets, tables, images, emails) from a wide range of document formats. It supports modern and legacy Microsoft Office files (.docx/.xlsx/.pptx and .doc/.xls/.ppt), PDFs, emails (.eml/.msg/.mbox), OpenDocument formats, HTML, and common plain-text formats — all through a single, unified API.\n\n*The key point: no LibreOffice, no Java, no shelling out. Just pip install and run. Everything is parsed directly in Python and exposed via generators for memory-efficient processing.*\n\n**Target Audience**\n\nDevelopers working with file extractions tasks. Lately these are in particular AI/RAG use-cases.\n\nTypical use cases:\n\n\\- RAG / LLM ingestion pipelines\n\n\\- SharePoint or file-share document indexing\n\n\\- Serverless workloads (AWS Lambda, GCP Functions)\n\n\\- Containerized services with tight image size limits\n\n\\- Security-restricted environments where subprocesses are a no-go\n\nIf you need to reliably extract text and structure from messy, real-world enterprise document collections — especially ones that still contain decades of legacy Office files — this is built for you.\n\n**Comparison**\n\nMost existing solutions rely on external tools:\n\n\\- LibreOffice-based pipelines require large system installs and fragile headless setups.\n\n\\- Apache Tika depends on Java and often runs as a separate service.\n\n\\- Subprocess-based wrappers add operational and security overhead.\n\nsharepoint-to-text takes a different approach:\n\n\\- Pure Python, no system dependencies\n\n\\- Works the same locally, in containers, and in serverless environments\n\n\\- One unified interface for all formats (no branching logic per file type)\n\n\\- Native support for legacy Office formats that are common in old SharePoint instances\n\nIf you want something lightweight, predictable, and easy to embed directly into Python applications — without standing up extra infrastructure — that’s the gap this library is trying to fill.\n\nLink: [https://github.com/Horsmann/sharepoint-to-text](https://github.com/Horsmann/sharepoint-to-text)"}
{"instruction": "I Made A 3D Renderer Using Pygame And No 3D Library", "input": "", "output": "I Made A 3D Renderer Using Pygame And No 3D Library\nBuilt a 3D renderer from scratch in Python. No external 3D engines, just Pygame and a lot of math.\n\n**What it does:**\n\n* Renders 3D wireframes and filled polygons at 60 FPS\n* First-person camera with mouse look\n* 15+ procedural shapes: mountains, fractals, a whole city, Klein bottles, Mandelbulb slices\n* Basic physics engine (bouncing spheres and collision detection)\n* OBJ model loading (somewhat glitchy without rasterizaton)\n\n**Try it:**\n\nbash\n\n    pip install aiden3drenderer\n\n\nPython\n\n    from aiden3drenderer import Renderer3D, renderer_type\n\n    renderer = Renderer3D()\n    renderer.render_type = renderer_type.POLYGON_FILL\n    renderer.run()\n\n\nPress number keys to switch terrains. Press 0 for a procedural city with 6400 vertices, R for fractals, T for a Klein bottle.\n\n**Comparison:**\nI dont know of other 3D rendering libraries, but this one isnt meant for production use, just as a fun visualization tool\n\n**Who's this for?**\n\n* Learning how 3D graphics work from first principles\n* Procedural generation experiments\n* Quick 3D visualizations without heavy dependencies\n* Understanding the math behind game engines\n\n**GitHub:** [https://github.com/AidenKielby/3D-mesh-Renderer](https://github.com/AidenKielby/3D-mesh-Renderer)\n\nFeedback is greatly appreciated"}
{"instruction": "Janus / Tachyon-RS - A git-like state tracker for python objects with a Rust backend", "input": "", "output": "Janus / Tachyon-RS - A git-like state tracker for python objects with a Rust backend\nHello all.  I've been working on a project and I wanted to share and know what your thoughts are on it.\n\n**TD;DR:** Janus is a python library that lets you branch, merge, and \"time-travel\" through the state of complex Python objects in a manner reminiscent of Git with *O*(1) overhead, powered by a Rust backend (Tachyon-RS).\n\n**What my project does:**\n\nMy project is called Janus / Tachyon-RS ([PyPi](https://pypi.org/project/janus-tachyon-rs/), [GitHub](https://github.com/goldenphoenix713/janus)), and it's a state-tracker for python objects. Basically, think Git for python objects. Every change in the object is saved as an operation and reverse operation, which lets you easily revert to earlier states. You can even revert to an earlier state and branch in a new direction to compare the different states. The name is a split of the forward facing API and the engine: Janus refers to the Python side, with access to the `TimelineBase` and `MultiverseBase` classes to use, as well as a plugin infrastructure to add objects from other libraries (currently, I have plugins for pandas and numpy state tracking). Tachyon-RS is the Rust side, and refers to the state-tracking code that saves the diffs during an object state change (so, just like Git). You can and label specific states to quickly move back to them and label branches to switch between them (again, just like Git). Because only the changes in state are saved, it's much more efficient that making a deep-copy, and it automatically tracks all changes, so there's no worries about forgetting to make a copy at a critical step - it's already done.\n\nMy inspiration for this project: I'm a data scientist, and I can't tell you how often I'll be working with some data, only for me to manipulate it some way that I then realize doesn't work and, hey, I didn't make a copy beforehand, so I have to start from the beginning, which can be annoying when loading data and cleaning takes quite some time. I always kept wanting an undo button. So with Janus, I made that undo button. But while I was working on it, I realized that the concept could be expanded to more than just a linear timeline of states, so I expanded the concept and it just kinda went from there. The really nice thing about the implementation I have is that because Janus only tracks the diffs, adding new states and reverting is done in *O*(1) time. Also, because I wanted to, I kinda went a bit hard on the \"time-travel\" and \"multiverse\" theming of the library, which I felt was appropriate.\n\nFull disclosure: I did have an AI assist with the code. The backend is written in Rust, which I'm fairly new to, so in order to get through the Rust code, I had an AI write some code. However, I'm very particular about the code style, and so I had a lot of rules in place that the AI had to follow, as well as strict typing rules with mypy and linting and formatting with ruff. There were also plenty of times where I did not like the direction it wanted to take things and so I had to rein it in or undo a lot of its changes to make something more aligned to what I had in mind. Much of the python side was written by me with some bit of assistance on the Rust-Python boundary and the plugins. I also am terrible at writing documentation but always want it to be good, so I had the AI do that (you'll notice it in the README, it's very AI-style, but I don't really know how to rewrite it oth"}
{"instruction": "What are your favorite lightweight Python desktop tools?", "input": "", "output": "What are your favorite lightweight Python desktop tools?\nLately I’ve been building small desktop utilities in Python instead of web apps and honestly I forgot how fun it is 😭\n\nI recently made a tiny FFmpeg helper for myself because I was tired of manually converting media files for projects. Main goal was just keeping it lightweight and runable on my old Linux laptop instead of using huge apps for simple tasks.\n\nMade me curious what lightweight Python desktop tools people here actually use regularly? Could be automation tools file managers media utilities anything."}
{"instruction": "PyWebLib editable code with Turtle and Game library support", "input": "", "output": "PyWebLib editable code with Turtle and Game library support\nI would love for some more feedback on the lightweight game library and turtle integration I built off of PyDiode.\n\nIt now works on Safari as well, you can create your own SVG assets , publish them to a database, then edit and publish code/games for free in the browser without needing to install anything.\n\nI work as a highschool teacher, and the junior year levels only have access to Chromebook laptops. [https://scratch.mit.edu/](https://scratch.mit.edu/) is banned, which obviously restricts a lot of the python coding-possibilities. Couldn't find a way to get a Python IDE onto a Chromebook, haha...\n\nIn terms of proud, so far I've got PacMan and Flappy bird shared to the community page/DB\n\nWould love to see people building with it, you can make something reminiscent of doom 3D in only 80 lines of code.\n\nIt's a bit hard to find , but you can't post repo links here because of the slop apparently. But I've got it indexed now it's possible to find."}
{"instruction": "Is SQLite’s `RETURNING` clause actually safe for concurrent atomic locks in a distributed system?", "input": "", "output": "Is SQLite’s `RETURNING` clause actually safe for concurrent atomic locks in a distributed system?\nI’ve been trying to avoid deploying Redis or RabbitMQ just to coordinate distributed background Python scripts across different machines.\n\nInstead, I built a pure HTTP job bus using Flask and SQLite, relying on SQLite’s `BEGIN IMMEDIATE` transaction and the `RETURNING` clause to claim jobs atomically. The goal is to make sure multiple concurrent polling workers do not grab the same task.\n\nHere is the exact locking query I’m using inside the route:\n\n```sql\nWITH candidate AS (\n    SELECT id\n    FROM intents\n    WHERE expires_at > :now\n      AND status != 'failed'\n      AND claim_attempts < :max_attempts\n      AND (status='open' OR (status='claimed' AND claimed_at < :stale))\n      AND (publisher=:worker_key OR visibility='public')\n    ORDER BY claim_attempts ASC, created_at ASC, id ASC\n    LIMIT 1\n)\nUPDATE intents\nSET status='claimed',\n    claimed_at=:now,\n    claimed_by=:claimer,\n    claim_attempts=claim_attempts+1\nWHERE id = (SELECT id FROM candidate)\n  AND claim_attempts < :max_attempts\n  AND (status='open' OR (status='claimed' AND claimed_at < :stale))\nRETURNING id, goal, payload, claim_attempts;\n```\n\n*(The database is running with `PRAGMA journal_mode=WAL;` and `PRAGMA busy_timeout=30000;`.)*\n\nI recently had to refactor the server to use synchronous lazy-evaluation for garbage collection because a background thread approach was causing WSGI zombie thread locks on PythonAnywhere. With that fixed, it works reliably on the free tier.\n\nMy question for the backend folks here is: at what scale does this single-writer SQLite approach actually start deadlocking or failing under HTTP concurrency? Has anyone successfully used SQLite as a message-broker-like coordination layer in production, or is `SQLITE_BUSY` basically inevitable?\n\n(I can drop the GitHub link in the comments if anyone wants to look at the Flask connection handling or the Strict Auth HMAC signing around it).\n\nI’d love to hear how you handle lightweight concurrency without pulling in heavy message brokers."}
{"instruction": "Just released Servy 5.9 - Turn Any Python App into a Native Windows Service", "input": "", "output": "Just released Servy 5.9 - Turn Any Python App into a Native Windows Service\nIt's been about six months since the initial announcement, and Servy 5.9 is released.\n\nThe community response has been amazing: 1,100+ stars on GitHub and 19,000+ downloads.\n\nIf you haven't seen Servy before, it's a Windows tool that turns any Python app (or other executable) into a native Windows service. You just set the Python executable path, add your script and arguments, choose the startup type, working directory, and environment variables, configure any optional parameters, click install, and you're done. Servy comes with a desktop app, a CLI, PowerShell integration, and a manager app for monitoring services in real time.\n\nIn this release (5.9), I've added/improved:\n\n* New [Console tab](https://github.com/aelassas/servy/wiki/Overview#console) to display real-time service `stdout` and `stderr` output\n* Pre-stop and post-stop hooks ([\\#36](https://github.com/aelassas/servy/issues/36))\n* Optimized CPU and RAM graphs performance and rendering\n* Keep the Service Control Manager (SCM) responsive during long-running process termination\n* Improve shutdown logic for complex process trees\n* Prevent orphaned/zombie child processes when the parent process is force-killed\n* Bug fixes and expanded documentation\n\nCheck it out on GitHub: [https://github.com/aelassas/servy](https://github.com/aelassas/servy)\n\nDemo video here: [https://www.youtube.com/watch?v=biHq17j4RbI](https://www.youtube.com/watch?v=biHq17j4RbI)\n\nPython sample: [https://github.com/aelassas/servy/wiki/Examples-&-Recipes#run-a-python-script-as-a-service](https://github.com/aelassas/servy/wiki/Examples-&-Recipes#run-a-python-script-as-a-service)\n\nAny feedback or suggestions are welcome."}
{"instruction": "I brought \"Resource\" primitives to Python for better async state management (reaktiv v0.21.0)", "input": "", "output": "I brought \"Resource\" primitives to Python for better async state management (reaktiv v0.21.0)\nHi everyone,\n\nI’m the maintainer of reaktiv, a reactive state management library for Python inspired by the DX of Angular Signals and SolidJS. I’ve just released v0.21.0, which introduces a major new primitive: Resource.\n\nIf you've ever dealt with the \"tangled web\" of managing loading states, error handling, and race conditions in async Python, this release is for you.\n\n# Why the Angular connection?\n\nThe Angular community has been doing incredible work with fine-grained reactivity. Their introduction of the resource() API solved a huge pain point: how to declaratively link a reactive variable (a Signal) to an asynchronous fetch operation. I wanted that exact same \"it just works\" experience in the Python ecosystem.\n\n# How it works: Push + Pull\n\nOne of the core strengths of reaktiv (and why it scales so well) is the combination of Push and Pull reactivity:\n\n\\- The Push: When a dependency (like a Signal) changes, it pushes a notification down the dependency graph to mark all related Computed or Resource values as \"dirty.\" It doesn't recalculate them immediately - it just lets them know they are out of date.\n\n\\- The Pull: The actual computation or async loading only happens when you pull (read) the value. If no one is listening to or reading the value, no work is done.\n\nThis hybrid approach ensures your app stays efficient - performing the minimum amount of work necessary to keep your state consistent.\n\n# What’s new in v0.21.0?\n\n \\- Resource Primitive: Automatically syncs async loaders with reactive state.\n\n\\- Built-in Loading States: Native .is\\_loading() and .value() signals.\n\n\\- Dependency Tracking: If the request signal changes, the loader is re-triggered automatically.\n\n\n\nI’d love to get your feedback on the API.\n\nGitHub: https://github.com/buiapp/reaktiv\n\nDocs: https://reaktiv.bui.app/"}
{"instruction": "I'm building 100 IoT projects in 100 days using MicroPython — all open source", "input": "", "output": "I'm building 100 IoT projects in 100 days using MicroPython — all open source\nWhat my project does:\n\n A 100-day challenge building and documenting real-world IoT projects using MicroPython on ESP32, ESP8266, and Raspberry Pi Pico. Every project includes wiring diagrams, fully commented code, and a README so anyone can replicate it from scratch.\n\nTarget audience:\n\nStudents and beginners learning embedded systems and IoT with Python. No prior hardware experience needed.\n\nComparison:\n\nUnlike paid courses or scattered YouTube tutorials, everything here is free, open-source, and structured so you can follow along project by project.\n\nSo far the repo has been featured in Adafruit's Python on Microcontrollers newsletter (twice!), highlighted at the Melbourne MicroPython Meetup, and covered on Hackster.io.\n\nRepo: [https://github.com/kritishmohapatra/100\\_Days\\_100\\_IoT\\_Projects](https://github.com/kritishmohapatra/100_Days_100_IoT_Projects)\n\nHardware costs add up fast as a student — sensors, boards, modules. If you find this useful or want to help keep the project going, I have a GitHub Sponsors page. Even a small amount goes directly toward buying components for future projects.\n\nNo pressure at all — starring the repo or sharing it means just as much. 🙏"}
{"instruction": "Sunday Daily Thread: What's everyone working on this week?", "input": "", "output": "Sunday Daily Thread: What's everyone working on this week?\n# Weekly Thread: What's Everyone Working On This Week? 🛠️\n\nHello 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!\n\n# How it Works:\n\n1. **Show & Tell**: Share your current projects, completed works, or future ideas.\n2. **Discuss**: Get feedback, find collaborators, or just chat about your project.\n3. **Inspire**: Your project might inspire someone else, just as you might get inspired here.\n\n# Guidelines:\n\n* Feel free to include as many details as you'd like. Code snippets, screenshots, and links are all welcome.\n* Whether it's your job, your hobby, or your passion project, all Python-related work is welcome here.\n\n# Example Shares:\n\n1. **Machine Learning Model**: Working on a ML model to predict stock prices. Just cracked a 90% accuracy rate!\n2. **Web Scraping**: Built a script to scrape and analyze news articles. It's helped me understand media bias better.\n3. **Automation**: Automated my home lighting with Python and Raspberry Pi. My life has never been easier!\n\nLet's build and grow together! Share your journey and learn from others. Happy coding! 🌟"}
{"instruction": "Anyone running free-threaded Python 3.14 in production yet? Curious what actually breaks", "input": "", "output": "Anyone running free-threaded Python 3.14 in production yet? Curious what actually breaks\nBeen testing the free-threaded build (3.14t) on some CPU-bound data processing work. The multi-core story is finally real after 30 years of GIL, but the friction is exactly what you'd expect: a couple of C-extension-heavy libs in my stack silently re-enable the GIL, and there's no clean way to detect that at runtime besides checking sys.\\_is\\_gil\\_enabled() manually.\n\nFor anyone who's shipped something on 3.14t, not just benchmarked it:\n\nWhat broke that you didn't expect?\n\nReal speedups outside toy examples, or mostly marginal so far?\n\nProd yet, or still just kicking the tires?\n\nNot fishing for a benchmark war. Genuinely curious what breaks in messy real codebases vs clean demos."}
{"instruction": "What's under your Python app - Postgres, SQLite, MySQL, MariaDB - and why? Yearly database survey", "input": "", "output": "What's under your Python app - Postgres, SQLite, MySQL, MariaDB - and why? Yearly database survey\n>Hey, Robert from the MariaDB Foundation here. We run a yearly survey on how people actually use MariaDB, and this year we also want to know in what cases they went with Postgres, SQLite, MySQL or whatever else instead:\n>\n>[https://mariadb.typeform.com/to/tS69UzVo?utm\\_source=reddit\\_python](https://mariadb.typeform.com/to/tS69UzVo?utm_source=reddit_python)\n>\n>There were a good number of Python and Django users on MariaDB in last year's survey - and a surprising third of them used no ORM at all. What database is under your Python app, and how did it get there? Did you pick it, did the framework default stick, or was it already on the server?\n>\n>We revamped the questions this year for new insights and split them by role (developer, DBA, operator) to save you time. Nearly 400 answers so far, keep them coming :) Looking forward to reading yours. Anonymous results will be published again at mariadb.org/survey.\n>\n>Thanks for taking the time!\nCheers, Robert at MariaDB Foundation"}
{"instruction": "Faster NumPy in the browser", "input": "", "output": "Faster NumPy in the browser\nSome of my colleagues worked on improving the performances of numpy running in the browser by using OpenBLAS.\nI let you check the article they wrote about that: [https://notebook.link/blog/the-last-mile-faster-numpy/](https://notebook.link/blog/the-last-mile-faster-numpy/)"}
{"instruction": "Converting from Pandas to Polars - Ressources", "input": "", "output": "Converting from Pandas to Polars - Ressources\nIn light of Pandas v3 and former Pandas core dev, Marc Garcia's blog post, that recommends Polars multiple times, I think it is time for me to inspect the new bear 🐻‍❄️\n\nUsually I would have read the whole documentation, but I am father now, so time is limited.\n\nWhat is the best ressource without heavy reading that gives me a good broad foundation of Polars?"}
{"instruction": "Python in the Browser is Peaking: A Look at Pyodide (Wasm)", "input": "", "output": "Python in the Browser is Peaking: A Look at Pyodide (Wasm)\nIf you’ve been following the WebAssembly (Wasm) space, you know the dream: running high-performance Python code without needing a backend server. [Pyodide](https://thepixelspulse.com/posts/pyodide-python-webassembly-benefits-tradeoffs/)is making this a reality by bringing the CPython interpreter directly to the client side.\n\n**The TL;DR:** Pyodide compiles the CPython interpreter and major scientific libraries (NumPy, Pandas, Matplotlib) into WebAssembly. It allows Python to run in the browser's JavaScript runtime, enabling bidirectional communication between the two.\n\n**Why it’s a game changer:**\n\n* **Zero-Server Interactivity:** Build data science demos or educational tools that don't need a server round-trip for every calculation.\n* **Massive Ecosystem:** Using `micropip`, you can install pure Python wheels and many C-extension packages directly in the browser.\n* **Edge Computing:** It’s not just for browsers anymore; it’s being used in Node.js and [Cloudflare Workers](https://thepixelspulse.com/posts/pyodide-python-webassembly-benefits-tradeoffs/) to run Python at the edge.\n\n**The Reality Check (The Trade-offs):**\n\n* **The \"Chonk\" Factor:** The initial bundle size is huge. Downloading a full interpreter and NumPy takes time, which can hurt initial page load speeds.\n* **Performance Hit:** While Wasm is fast, Python via Pyodide is still slower than native Python on a desktop. It's not the best choice for extreme \"heavy lifting.\"\n* **Dependency Hell:** Not every PyPI package is compatible with the Wasm environment yet, though the list is growing.\n\n**Is it worth it?** If you're building interactive notebooks, sandboxed coding environments, or client-side data viz, absolutely. For a standard CRUD app? Stick to a traditional backend for now.\n\n\nTell me your thoughts.\n\n**Citing the source:**[Pixels and Pulse](https://thepixelspulse.com/posts/pyodide-python-webassembly-benefits-tradeoffs/)"}
{"instruction": "would you be interested in free interactive course on Pydantic?", "input": "", "output": "would you be interested in free interactive course on Pydantic?\nwhile the docs are amazing and Pydantic itself is not that complex, i still want to do something, you know, for the community. but i don't know if there would be ANY demand for it. i'm gonna continue working on it anyway (it's almost ready to be released). however i would still appreciate some minimal opinion\n\nfor some reason i can't post images here, so i'll clarify what i mean by \"interactive\" with words. the left side of the screen is a lesson body with theoretical information and a little problem in the end. the right side of the screen is a little code executor with syntax highlighting, actual code execution in the backend and stuff"}
{"instruction": "Why is GPU Python packaging still this broken?", "input": "", "output": "Why is GPU Python packaging still this broken?\nI keep running into the same wall over and over and I know I’m not the only one.\n\nEven with Docker, Poetry, uv, venvs, lockfiles, and all the dependency solvers, I still end up compiling from source and monkey patching my way out of dependency conflicts for AI/native Python libraries. The problem is not basic Python packaging at this point. The problem is the compatibility matrix around native/CUDA packages and the fact that there still just are not wheels for a lot of combinations you would absolutely expect to work.\n\nSo then what happens is you spend hours juggling Python, torch, CUDA, numpy, OS versions, and random transitive deps trying to land on the exact combination where something finally installs cleanly. And if it doesn’t, now you’re compiling from source and hoping it works. I have lost hours on an H100 to this kind of setup churn and it's expensive.\n\nAnd yeah, I get that nobody can support every possible environment forever. That’s not really the point. There are obviously recurring setups that people hit all the time - common Colab runtimes, common Ubuntu/CUDA/Torch stacks, common Windows setups. The full matrix is huge, but the pain seems to cluster around a smaller set of packages and environments.\n\nWhat’s interesting to me is that even with all the progress in Python tooling, a lot of the real friction has just moved into this native/CUDA layer. Environment management got better, but once you fall off the happy path, it’s still version pin roulette and fragile builds.\n\nIt just seems like there’s still a lot of room for improvement here, especially around wheel coverage and making the common paths less brittle. Not pushing a solution just venting."}
{"instruction": "Move a project sync'd with uv for offline use.", "input": "", "output": "Move a project sync'd with uv for offline use.\nMost modern projects on GitHub tend to use `uv` instead of pip.\n\nwith pip I could do\n\n1. create `venv`.\n\n2. `pip install <package>`\n\n3. `pip freeze > requirements.txt`\n\n4. `pip wheel -r requirements.txt`\n\nand then move the whole wheel folder to the offline PC.\n\n5. And create a `venv` there\n\n6. `pip install -r requirements.txt --no-index --find-links <path_to_wheel_folder>`\n\nI haven't had success with `uv` based projects running offline.\n\nI realize that `uv` has something like `uv pip` but the `download` and `wheel` options are missing."}
{"instruction": "I made Python serialization and parallel processing easy even for beginners", "input": "", "output": "I made Python serialization and parallel processing easy even for beginners\nI have worked for the past year and a half on a project because I was tired of PicklingErrors, multiprocessing BS and other things that I thought could be better.\n\nGithub: https://github.com/ceetaro/Suitkaise\n\nOfficial site: suitkaise.info\n\nNo dependencies outside the stdlib.\n\nI especially recommend using Share:\n```python\nfrom suitkaise import Share\n\nshare = Share()\nshare.anything = anything\n\n# now that \"anything\" works in shared state\n```\n\n## What my project does\n\nMy project does a multitude of things and is meant for production. It has 6 modules: cucumber, processing, timing, paths, sk, circuits.\n\n### cucumber: serialization/deserialization engine that handles:\n\n- handling of additional complex types (even more than dill)\n- speed that far outperforms dill\n- serialization and reconstruction of live connections using special Reconnector objects\n- circular references\n- nested complex objects\n- lambdas\n- closures\n- classes defined in main\n- generators with state\n- and more\n\n#### Some benchmarks\n\nAll benchmarks are available to see on the site under the cucumber module page \"Performance\".\n\nHere are some results from a benchmark I just ran:\n\n- dataclass: 67.7µs (2nd place: cloudpickle, 236.5µs)\n- slots class: 34.2µs (2nd place: cloudpickle, 63.1µs)\n- bool, int, float, complex, str, and bytes are all faster than cloudpickle and dill\n- requests.Session is faster than regular pickle\n\n### processing: parallel processing, shared state\n\n#### Skprocess: improved multiprocessing class\n\n- uses cucumber, for more object support\n- built in config to set number of loops/runs, timeouts, time before rejoining, and more\n- lifecycle methods for better organization\n- built in error handling organized by lifecycle method\n- built in performance timing with stats\n\n#### Share: shared state\n\n1. Create a Share object (share = Share())\n2. add objects to it as you would a regular class (share.anything = anything)\n3. pass to subprocesses or pool workers\n4. use/update things as you would normally.\n\n- supports wide range of objects (using cucumber)\n- uses a coordinator system to keep everything in sync for you\n- easy to use\n\n#### Pool\n\nupgraded multiprocessing.Pool that accepts Skprocesses and functions.\n\n- uses cucumber (more types and freedom)\n- has modifiers, incl. star() for tuple unpacking\n\n### also...\n\nThere are other features like...\n- timing with one line and getting a full statistical analysis\n- easy cross plaform pathing and standardization\n- cross-process circuit breaker pattern and thread safe circuit for multithread rate limiting\n- decorator that gives a function or all class methods modifiers without changing definition code (.asynced(), .background(), .retry(), .timeout(), .rate_limit())\n\n## Target audience\n\nIt seems like there is a lot of advanced stuff here, and there is. But I have made it easy enough for beginners to use. This is who this project targets:\n\n### Beginners!\n\nI have made this easy enough for beginners to create complex parallel programs without needing to learn base multiprocessing. By using Skprocess and Share, everything becomes a lot simpler for beginner/low intermediate level users.\n\n### Users doing ML, data processing, or advanced parallel processing\n\nThis project gives you API that makes prototyping and developing parallel code significantly easier and faster. Advanced users will enjoy the freedom and ease of use given to them by the cucumber serializer."}
{"instruction": "italian-tax-validators: Italian Codice Fiscale & Partita IVA validation for Python — zero deps", "input": "", "output": "italian-tax-validators: Italian Codice Fiscale & Partita IVA validation for Python — zero deps\nIf you've ever had to deal with Italian fiscal documents in a Python project, you know the pain. The Codice Fiscale (CF) alone is a rabbit hole — omocodia handling, check digit verification, extracting birthdate/gender/birth place from a 16-character string... it's a lot.\n\nSo I built italian-tax-validators to handle all of it cleanly.\n\n**What My Project Does**\n\nA Python library for validating and generating Italian fiscal identification documents — Codice Fiscale (CF) and Partita IVA (P.IVA).\n\n* Validate and generate Codice Fiscale (CF)\n* Validate Partita IVA (P.IVA) with Luhn algorithm\n* Extract birthdate, age, gender, and birth place from CF\n* Omocodia handling (when two people share the same CF, digits get substituted with letters — fun stuff)\n* Municipality database with cadastral codes\n* CLI tool for quick validations from the terminal\n* Zero external dependencies\n* Full type hints, Python 3.9+\n\nQuick example:\n\n    from italian_tax_validators import validate_codice_fiscale\n\n    result = validate_codice_fiscale(\"RSSMRA85M01H501Q\")\n    print(result.is_valid)              # True\n    print(result.birthdate)             # [PHONE]\n    print(result.gender)                # \"M\"\n    print(result.birth_place_name)      # \"ROMA\"\n\nWorks out of the box with Django, FastAPI, and Pydantic — integration examples are in the README.\n\n**Target Audience**\n\nDevelopers working on Italian fintech, HR, e-commerce, healthcare, or public administration projects who need reliable, well-tested fiscal validation. It's production-ready — MIT licensed, fully tested, available on PyPI.\n\n**Comparison**\n\nThere are a handful of older libraries floating around (python-codicefiscale, stdnum), but most are either unmaintained, cover only validation without generation, or don't handle omocodia and P.IVA in the same package. italian-tax-validators covers the full workflow — validate, generate, extract metadata, look up municipalities — with a clean API and zero dependencies.\n\n**Install:**\n\n    pip install italian-tax-validators\n\nGitHub: [https://github.com/thesmokinator/italian-tax-validators](https://github.com/thesmokinator/italian-tax-validators)\n\nFeedback and contributions are very welcome!"}
{"instruction": "Benchmarked: 10 Python Dependency Injection libraries vs Manual Wiring (50 rounds x 100k requests)", "input": "", "output": "Benchmarked: 10 Python Dependency Injection libraries vs Manual Wiring (50 rounds x 100k requests)\nHi /r/python!\n\nDI gets flak sometimes around here for being overengineered and adding overhead. I wanted to know how much it actually adds in a real stack, so I built a benchmark suite to find out.\n\nFull disclosure, I maintain [Wireup](https://github.com/maldoinc/wireup), which is also in the race. The benchmark covers 10 libraries plus manual wiring via globals/creating objects yourself as an upper bound, so you can draw your own conclusions.\n\nTesting is done within a FastAPI + Uvicorn environment to measure performance in a realistic web-based environment. Notably, this also allows for the inclusion of fastapi.Depends in the comparison, as it is the most popular choice by virtue of being the FastAPI default.\n\nThis tests the full integration stack using a dense graph of 7 dependencies, enough to show variance between the containers, but realistic enough to reflect a possible dependency graph in the real world. This way you test container resolution, scoping, lifecycle management, and framework wiring in real FastAPI + Uvicorn request/response cycles. Not a microbenchmark resolving the same dependency in a tight loop.\n\n---\n\nTable below shows Requests per second achieved as well as the secondary metrics:\n\n- **RPS (Requests Per Second)**: The number of requests the server can handle in one second. **Higher is better.**\n- **Latency (p50, p95, p99)**: The time it takes for a request to be completed, measured in milliseconds. **Lower is\n    better.**\n- **σ (Standard Deviation)**: Measures the stability of response times (Jitter). A lower number means more consistent\n    performance with fewer outliers. **Lower is better.**\n- **RSS Memory Peak (MB)**: The highest post-iteration RSS sample observed across runs. **Lower is better.**\n    This includes the full server process footprint (Uvicorn + FastAPI app + framework runtime), not only service objects.\n\n**Per-request injection** (new dependency graph built and torn down on every request):\n\n| Project | RPS (Median Run) | P50 (ms) | P95 (ms) | P99 (ms) | σ (ms) | Mem Peak |\n| :--- | :--- | :--- | :--- | :--- | :--- | :--- |\n| **Manual Wiring (No DI)** | 11,[PHONE]%) | 4.20 | 4.50 | 4.70 | 0.70 | 52.93 MB |\n| **Wireup** | 11,[PHONE]%) | 4.20 | 4.50 | 4.70 | 0.83 | 53.69 MB |\n| **Wireup Class-Based** | 10,[PHONE]%) | 4.30 | 4.50 | 4.70 | 0.70 | 53.80 MB |\n| **Dishka** | 8,[PHONE]%) | 5.30 | 6.30 | 9.40 | 1.30 | 103.23 MB |\n| **Svcs** | 8,[PHONE]%) | 5.70 | 6.00 | 6.20 | 0.93 | 67.09 MB |\n| **Aioinject** | 8,[PHONE]%) | 5.60 | 6.60 | 10.40 | 1.31 | 100.52 MB |\n| **diwire** | 7,[PHONE]%) | 6.50 | 6.90 | 7.10 | 1.07 | 58.22 MB |\n| **That Depends** | 4,[PHONE]%) | 9.80 | 10.40 | 10.60 | 0.59 | 53.82 MB |\n| **FastAPI Depends** | 3,[PHONE]%) | 12.30 | 13.80 | 14.10 | 1.39 | 57.68 MB |\n| **Injector** | 3,[PHONE]%) | 15.20 | 15.40 | 16.10 | 0.58 | 53.52 MB |\n| **Dependency Injector** | 2,[PHONE]%) | 19.10 | 19.70 | 20.10 | 0.75 | 60.55 MB |\n| **Lagom** | 898 (8.13%) | 55.30 | 57.20 | 58.30 | 1.63 | 1.32 GB |\n\n---\n\n**Singleton injection** (cached graph, testing container bookkeeping overhead):\n\n- Manual Wiring: **13,351 RPS**\n- Wireup Class-Based: **13,342 RPS**\n- Wireup: **13,214 RPS**\n- Dependency Injector: **6,905 RPS**\n- FastAPI Depends: **6,153 RPS**\n\n---\n\nThe full page goes much deeper: stability tables across all 50 runs, memory usage, methodology, feature completenes"}
{"instruction": "pytest‑difftest — a pytest plugin to run only tests affected by code changes", "input": "", "output": "pytest‑difftest — a pytest plugin to run only tests affected by code changes\nGitHub: [https://github.com/yourusername/pytest-difftest](https://github.com/yourusername/pytest-difftest)\nPyPI: [https://pypi.org/project/pytest-difftest](https://pypi.org/project/pytest-difftest)\n\nWhat My Project Does\n\npytest‑difftest is a plugin for pytest that executes only the tests affected by recent code changes instead of running the whole suite. It determines which tests to run by combining hash of code blocks and coverage results. The goal is to reduce feedback time in development and for agentic coding to not skip any relevant tests.\n\nTarget Audience\n\nThis tool is intended for solo developers and teams using pytest who want faster test runs, especially in large codebases where running the full suite is costly. The project is experimental and in part vibecoded but usable for real workflows.\n\nComparison\n\npytest‑difftest is largely inspired by pytest‑testmon’s approach, but aims to be faster in large codebases and adds support for storing a test baseline in the cloud that can be shared."}
{"instruction": "Snacks for Python - a cli tool for DRY Python snippets", "input": "", "output": "Snacks for Python - a cli tool for DRY Python snippets\nI'm prepping to do some freelance web dev work in Python, and I keep finding myself re-writing the same things across projects — Google OAuth flows, contact form handlers, newsletter signup, JWT helpers, etc. So I did a thing.\n\n**What My Project Does**\n\nI didn't want to maintain a shared library (versioning across client projects is a headache), so I made a private Git repo of self-contained \\`.py\\` files I can just copy in as needed. **Snacks** is a small CLI tool I built to make that workflow faster.\n\n`snack stash create` — register a named stash directory where the snacks (snippets) are stored\n\n`snack unpack` — copy a snippet from your stash into the current project\n\n`snack pack` — push an improved snippet back to the library after working on it in a project\n\nYou can keep a stash locally or on github, either private or public repo.\n\nSource and wiki: [github.com/kickash/code/python-snacks](http://github.com/kickash/code/python-snacks)\n\n**Target Audience**\n\nThis is just a toy project for fun, but I thought I would share and get feedback.\n\n**Comparison** \n\nI know there's PyCharm and IDE managed code snippets, but I like to manage my files from the command line, which is where Snacks is different. Super light weight, just install with pip. It's not complicated and doesn't require any setup steps besides creating the stash and adding the snacks."}
{"instruction": "Fast Hilbert curves in Python (Numba): ~1.8 ns/point, 3–4 orders faster than existing PyPI packages", "input": "", "output": "Fast Hilbert curves in Python (Numba): ~1.8 ns/point, 3–4 orders faster than existing PyPI packages\n# What My Project Does\n\nWhile building a query engine for spatial data in Python, I needed a way to serialize the data (2D/3D → 1D) while preserving spatial locality so it can be indexed efficiently.\n\nI chose **Hilbert space-filling curves**, since they generally preserve locality better than Z-order (Morton) curves. The downside is that Hilbert mappings are more involved algorithmically and usually more expensive to compute.\n\nSo I built **HilbertSFC**, a high-throughput Hilbert encoder/decoder fully in Python using `numba`, optimized for kernel structure and compiler friendliness. It achieves:\n\n* \\~**1.8 ns/pt (\\~8 CPU cycles)** for 2D encode/decode (32-bit)\n* **\\~500M–4B points/sec** single-threaded depending on number of bits/dtype\n* **Multi-threaded throughput saturates memory-bandwidth**. It can’t get faster than reading coordinates and writing indices\n* **3–4 orders of magnitude faster** than existing Python packages\n* **\\~6× faster** than the Rust crate `fast_hilbert`\n\n# Target Audience\n\nHilbertSFC is aimed at Python developers and engineers who need:\n\n* High-performance spatial indexing or point-cloud processing\n* A pure-Python/Numba solution without requiring compiled extensions or external dependencies\n* Production-ready performance for large datasets, not just a toy or experimental library\n\nIt is suitable in domains such as **scientific computing, GIS, spatial databases, or machine learning** where locality-preserving indexing is required.\n\n# Comparison\n\nI benchmarked HilbertSFC against existing Python and Rust implementations:\n\n***2D Points - Random, nbits=32, n=5,000,000***\n\n|Implementation|ns/pt (enc)|ns/pt (dec)|Mpts/s (enc)|Mpts/s (dec)|\n|:-|:-|:-|:-|:-|\n|🔥 **hilbertsfc (multi-threaded)**|0.53|0.57|1883.52|1742.08|\n|🔥 **hilbertsfc (Python)**|1.84|1.88|543.60|532.77|\n|fast\\_hilbert (Rust)|12.24|12.03|81.67|83.11|\n|hilbert\\_2d (Rust)|121.23|101.34|8.25|9.87|\n|hilbert-bytes (Python)|2997.51|2642.86|0.334|0.378|\n|numpy-hilbert-curve (Python)|7606.88|5075.08|0.131|0.197|\n|hilbertcurve (Python)|14355.76|10411.20|0.0697|0.0961|\n\n***System:*** *Intel Core Ultra 7 258v, Ubuntu 24.04.4, Python 3.12.12, Numba 0.63.*\n\nFull benchmark methodology: [https://github.com/remcofl/HilbertSFC/blob/main/benchmark.md](https://github.com/remcofl/HilbertSFC/blob/main/benchmark.md)\n\n**Why HilbertSFC is faster than Rust implementations:** The speedup is actually not due to language choice, as both Rust and Numba lower through LLVM. Instead, it comes from architectural optimizations, including:\n\n* Fixed-structure finite state machine\n* State-independent LUT indexing (L1-cache friendly)\n* Fully unrolled inner loops\n* Bit-plane tiling\n* Short dependency chains\n* Vectorization-friendly loops\n\nIn contrast, Rust implementations rely on state-dependent LUTs inside variable-bound loops with runtime bit skipping, limiting instruction-level parallelism and (aggressive) unrolling/vectorization.\n\n# Source Code\n\n[https://github.com/remcofl/HilbertSFC](https://github.com/remcofl/HilbertSFC)\n\n# Example Usage (2D data)\n\n    from hilbertsfc import hilbert_encode_2d, hilbert_decode_2d\n\n    index = hilbert_encode_2d(17, 23, nbits=10)  # index = 534\n    x, y = hilbert_decode_2d(index, nbits=10)    # x, y = (17, 23)"}
{"instruction": "Composable, reusable WebSocket components for any ASGI framework (Django, FastAPI, Litestar)", "input": "", "output": "Composable, reusable WebSocket components for any ASGI framework (Django, FastAPI, Litestar)\nHi all, I'm the maintainer of a small channels (WebSocket) extension library for Django (and FastAPI too). While using and maintaining it, I started thinking it could become a small framework as well: composable and framework-independent, so it could be reused across Django/FastAPI/Litestar/... as long as the framework supports ASGI. Before going further, I'm putting the blueprint out here to compare notes with people who work with WebSockets regularly. If you have ever worked with WebSockets, I hope you can share any ideas, info, pain points, or suggestions you have.\n\nPrerequisites, what my library already has:\n\n* Function-like handlers rather than `while True` \\+ if/else\n* Automatic AsyncAPI doc generation\n* Full type hints\n* A testing kit\n* Support for all ASGI-based frameworks (Django, FastAPI, ...)\n\nAt a glance, it looks like this:\n\n    @ws_handler(output_type=ChatNotificationMessage)\n    async def handle_chat(self, message: ChatMessage) -> None:\n        # Automatically routed, validated, and type-safe\n        await self.broadcast_message(\n            ChatNotificationMessage(payload=message.payload)\n        )\n\n    @ws_handler\n    async def handle_ping(self, message: PingMessage) -> PongMessage:\n        return PongMessage()  # Auto-documented in AsyncAPI\n\nIf you have ever worked with WebSockets, I think you get the idea of what it does here.\n\nRecently I added the Topic feature, which is composable and reusable. It came out of a multiplexing feature request, and I was inspired by Phoenix Channels. It looks something like this:\n\n    class DiscussionTopic(Topic):\n        pattern = \"discussion:{pk}\"\n\n        async def authorize(self, pk: str) -> bool:\n            return await user_can_view(self.scope[\"user\"], pk)\n\n        @ws_handler\n        async def handle_reply(self, message: ReplyMessage) -> ReplyCreatedMessage:\n            return ReplyCreatedMessage(payload=message.payload)\n\n        @event_handler\n        async def handle_new_reply(self, event: NewReplyEvent) -> ReplyCreatedMessage:\n            return ReplyCreatedMessage(payload=event.payload)\n\nAnd you use it like this:\n\n    class HubConsumer(AsyncJsonWebsocketConsumer):\n        authenticator_class = JWTAuthenticator\n        topics = [DiscussionTopic, RoomTopic]\n\nIn short, topics let you multiplex: subscribe, publish messages, unsubscribe, and so on, all over the same socket. So you can reuse a single WebSocket connection and just add or compose multiple topics, i.e. multiple WebSocket handlers.\n\nThat made me think: if we could create reusable topics such as Notification, Streaming, Voice, AI Agent, and so on, which users could easily install or copy and then modify or inherit from in a structured way, WebSocket handling would become much more structured and easier. The idea is similar to DRF and its ecosystem, and the composable/reusable part would work like shadcn: copy it, own it, and modify the code freely.\n\nWhat would you use it for? As I mentioned above: notifications, streaming, voice, AI agents, and so on. I have done a lot of WebSocket work, and I keep having to redefine the same things over and over. There is no reusable approach like the ones we have for REST APIs. Another example is using Pydantic AI with the AG-UI protocol but over WebSockets, defined in a reusable way.\n\nSo, if you already know of an existing open source solution or library similar to this idea,"}
{"instruction": "Kontra: a Python library for data quality validation on files and databases", "input": "", "output": "Kontra: a Python library for data quality validation on files and databases\n# What My Project Does\n\nKontra is a data quality validation libarary and CLI. You define rules in YAML or Python and run them against datasets(Parquet, Postgres, SQL SERVER, CSV), and get back violation counts, sampled failing rows, and more.\n\nIt is designed to avoid unnecessary work. Some checks can be answered from file or database metadata and other are pushed down to SQL. Rules that cannot be validated with SQL or metadata, fall back to in-memory validation using Polars, loading only the required columns.\n\nUnder the hood it uses DuckDB for SQL pushdown on files.\n\n# Target Audience\n\nKontra is intended for production use in data pipelines and ETL jobs. It acts like a lightweight unit test for data, fast validation and profiling that measures dataset properties with out trying to enforce some policy or make decisions.\n\nIts is designed to be built on top of, with structured results that can be consumed by pipelines or automated workflows. It´s agood fir for anyone who needs fast validation or quick insight into data.\n\n# Comparison\n\nThere are several tools and frameworks for data quality that are often designed as a broader platforms with their own workflows and conventions. Kontra is smaller in scope. It focuses on fast measurement and reporting, with an execution model that separates metadata-based checks, SQL pushdown and in-memory validation.\n\nGitHub: [https://github.com/Saevarl/Kontra](https://github.com/Saevarl/Kontra)\nPyPI: [https://pypi.org/project/kontra/](https://pypi.org/project/kontra/)"}
{"instruction": "I built a tool to automatically tailor your resume to a job description using Python", "input": "", "output": "I built a tool to automatically tailor your resume to a job description using Python\n**What My Project Does**\n\nHello all, I got tired of curating my Resume to increase the odds that I get past ATS and HR. Before I would select the points that are relevant, change the tools highlighted and make sure it was still grammatically correct. It took about 15+ minutes for each one. I got frustrated and thought that I should be able to use an LLM to do the selection for me. So I built out this project.\n\n**Target Audience**\n\nThe project is small and barebones. I wanted to keep the project small so that other technical people could read, understand and add on to it. Which is why I also have a fair amount of documentation. Despite it being barebones the workflow is fairly nice and intuitive. You can see a demo of it in the repo.\n\n**Comparison**\n\nThere are a few other resume selectors. I listed them in the repo. However I still wanted to create this one because I thought that they lacked:\n- Template flexibility\n\n- LLM flexibility\n\n- Extendability\n\nIf you have any questions let me know. If you have any feedback it would be greatly appreciated.\n\nGithub Repo: https://github.com/farmerTheodor/Resume-Tailor"}
{"instruction": "Carpet Python Enclosure Setup", "input": "", "output": "Carpet Python Enclosure Setup\nHi there, new here and just wondering what you guys think of my python enclosure setup? It is a 4x2x2 with a heat lamp, uvb, 3 hiding areas, a water bowl and plenty of fake plants. If there is anything wrong with it please let me know"}
{"instruction": "Improved markdown quality, code intelligence for 248 languages, and more in Kreuzberg v4.7.0", "input": "", "output": "Improved markdown quality, code intelligence for 248 languages, and more in Kreuzberg v4.7.0\nKreuzberg v4.7.0 is here. Kreuzberg is a Rust-core document intelligence library with bindings for Python, TypeScript/Node.js, Go, Ruby, Java, C#, PHP, Elixir, R, C, and WASM. \n\nWe’ve added several features, integrated OpenWEBUI, and made a big improvement in quality across all formats. There is also a new markdown rendering layer and new HTML output, which we now support. And many other fixes and features (find them in our [the release notes](https://github.com/kreuzberg-dev/kreuzberg/releases)).\n\nThe main highlight is **code intelligence and extraction.** Kreuzberg now supports 248 formats through our [tree-sitter-language-pack library](https://github.com/kreuzberg-dev/tree-sitter-language-pack). This is a step toward making Kreuzberg an engine for agents. You can efficiently parse code, allowing direct integration as a library for agents and via MCP. AI agents work with code repositories, review pull requests, index codebases, and analyze source files. Kreuzberg now extracts functions, classes, imports, exports, symbols, and docstrings at the AST level, with code chunking that respects scope boundaries. \n\nRegarding **markdown quality**, poor document extraction can lead to further issues down the pipeline. We created a benchmark harness using Structural F1 and Text F1 scoring across over 350 documents and 23 formats, then optimized based on that. LaTeX improved from 0% to 100% SF1. XLSX increased from 30% to 100%. PDF table SF1 went from 15.5% to 53.7%. All 23 formats are now at over 80% SF1. The output pipelines receive is now structurally correct by default. \n\nKreuzberg is now available as a document extraction backend for OpenWebUI, with options for docling-serve compatibility or direct connection. This was one of the most requested integrations, and it’s finally here. \n\nIn this release, we’ve added unified architecture where every extractor creates a standard typed document representation. We also included TOON wire format, which is a compact document encoding that reduces LLM prompt token usage by 30 to 50%, semantic chunk labeling, JSON output, strict configuration validation, and improved security. GitHub: [https://github.com/kreuzberg-dev/kreuzberg](https://github.com/kreuzberg-dev/kreuzberg). \n\n [https://kreuzberg.dev](https://kreuzberg.dev)\n\nContributions are always very welcome!"}
{"instruction": "The Elm Architecture in Python?", "input": "", "output": "The Elm Architecture in Python?\nSince I've fallen in love with Rust's \\`iced\\` recently, I've been wondering if there's been any implementations of native TEA for Python. As it is with such things, I immediately wanted to jump into making my own wrapper around Tkinter, but I figured it'd be wiser to ask first!"}
{"instruction": "GUI based Python Tkinter Serial Port Program for communicating with Arduino Microcontroller from PC", "input": "", "output": "GUI based Python Tkinter Serial Port Program for communicating with Arduino Microcontroller from PC\nI recently created a Python Serial Communication program with GUI (Graphical User Interface) based on the Tkinter Library with ttkbootstrap theming .\n\nThe Python Tkinter Serial Port Program can communicate with an Arduino or other Microcontroller boards via serial port to send and receive the data from your PC.\n\nYou can find the [link to the GUI here](https://www.xanthium.in/sites/default/files/inline-images/python-tkinter-serial-port-monitor.jpg).\n\n[Full tutorial along with Source Code here ](https://www.xanthium.in/simple-gui-based-python-tkinter-ttkbootstrap-serialport-communication-arduino-uart-microcontroller)\n\n[Youtube Tutorial for Python Tkinter Serial Port Programming here ](https://www.youtube.com/watch?v=iKMPLOqGa0U)"}
{"instruction": "What's your testing philosophy for scripts vs. production-grade Python code?\"", "input": "", "output": "What's your testing philosophy for scripts vs. production-grade Python code?\"\nFor a small script, I usually just run it with a few inputs and check whether the output looks correct. But for production code, I assume testing needs to be much more structured."}
{"instruction": "I built a local-first file metadata extraction library with a CLI (Python + Pydantic + Typer)", "input": "", "output": "I built a local-first file metadata extraction library with a CLI (Python + Pydantic + Typer)\nHi all,\n\nI've been working on a project called Dorsal for the last 18 months. It's a way to make unstructured data more queryable and organized, without having to upload files to a cloud bucket or pay for remote compute (my CPU/GPU can almost always handle my workloads).\n\n# What my Project Does\n\nDorsal is a Python library and CLI for generating, validating and managing structured file metadata. It scans files locally to generate validated JSON-serializable records. I personally use it for deduplicating files, adding annotations (structured metadata records) and organizing files by tags.\n\n* Core Extraction: Out of the box, it extracts \"universal\" metadata (Name, Hashes, Media Type; things any file has), as well and format-specific values (e.g., document page counts, video resolution, ebook titles/authors).\n* The Toolkit: It provides the scaffolding to build and plug in your own complex extraction models (like OCR, classification, or entity extraction, where the input is a file). It handles the pipeline execution, dependency management, and file I/O for you.\n* Strict Validation: It enforces Pydantic/JSON Schema on all outputs. If your custom extractor returns a float where a string is expected, Dorsal catches it before it pollutes your index.\n\nExample: a simple custom model for checking PDF files for sensitive words:\n\n    from dorsal import AnnotationModel\n    from dorsal.file.helpers import build_classification_record\n    from dorsal.file.preprocessing import extract_pdf_text\n\n    SENSITIVE_LABELS = {\n        \"Confidential\": [\"confidential\", \"do not distribute\", \"private\"],\n        \"Internal\": [\"internal use only\", \"proprietary\"],\n    }\n\n    class SensitiveDocumentScanner(AnnotationModel):\n        id: str = \"github:dorsalhub/annotation-model-examples\"\n        version: str = \"1.0.0\"\n\n        def main(self) -> dict | None:\n            try:\n                pages = extract_pdf_text(self.file_path)\n            except Exception as err:\n                self.set_error(f\"Failed to parse PDF: {err}\")\n                return None\n\n            matches = set()\n            for text in pages:\n                text = text.lower()\n                for label, keywords in SENSITIVE_LABELS.items():\n                    if any(k in text for k in keywords):\n                        matches.add(label)\n\n            return build_classification_record(\n                labels=list(matches),\n                vocabulary=list(SENSITIVE_LABELS.keys())\n            )\n\n\\^ This can be easily integrated into a locally-run linear pipeline, and executed via either the command line (by pointing at a file or directory) or in a python script.\n\n# Target Audience\n\n* ML Engineers / Data Scientists: Dorsal lets you make sure all of your output steps are validated, using a set of robust schemas for many common data engineering tasks (regression, entity extraction, classification etc.).\n* Data Hoarders / Archivists: People with massive local datasets (TB+) who like customizable tools for deduplication, tagging and even cloud querying\n* RAG Pipeline Builders: Turn folders of PDFs and docs into structured JSON chunks for vector embeddings\n\n# Links\n\n* Github: [https://github.com/dorsalhub/dorsal](https://github.com/dorsalhub/dorsal)\n* PyPI: pip install dorsalhub\n* Docs: [https://docs.dorsalhub.com](https://docs.dorsalhub.com)\n\n# Comparison\n\n|Feature|Dorsal|Cloud ETL (AWS/GCP)|\n|:-"}
{"instruction": "I mapped Google NotebookLM's internal RPC protocol to build a Python Library", "input": "", "output": "I mapped Google NotebookLM's internal RPC protocol to build a Python Library\nHey r/Python,\n\nI've been working on notebooklm-py, an unofficial Python library for Google NotebookLM.\n\n**What My Project Doe**s\n\nIt's a fully async Python library (and CLI) for Google NotebookLM that lets you:\n\n* Bulk import sources: URLs, PDFs, YouTube videos, Google Drive files\n* Generate content: podcasts (Audio Overviews), videos, quizzes, flashcards, study guides, mind maps\n* Chat/RAG: Ask questions with conversation history and source citations\n* Research mode: Web and Drive search with auto-import\n\nNo Selenium, no Playwright at runtime—just pure httpx. Browser is only needed once for initial Google login.\n\n**Target Audience**\n\n* Developers building RAG pipelines who want NotebookLM's document processing\n* Anyone wanting to automate podcast generation from documents\n* AI agent builders - ships with a Claude Code skill for LLM-driven automation\n* Researchers who need bulk document processing\n\nBest for prototypes, research, and personal projects. Since it uses undocumented APIs, it's not recommended for production systems that need guaranteed uptime.\n\n**Comparison**\n\nThere's no official NotebookLM API, so your options are:\n\n* Selenium/Playwright automation: Works but is slow, brittle, requires a full browser, and is painful to deploy in containers or CI.\n* This library: Lightweight HTTP calls via httpx, fully async, no browser at runtime. The tradeoff is that Google can change the internal endpoints anytime—so I built a test suite that catches breakage early.\n   * VCR-based integration tests with recorded API responses for CI\n   *   Daily E2E runs against the real API to catch breaking changes early\n   *   Full type hints so changes surface immediately\n\n**Code Example**\n\n    import asyncio\n    from notebooklm import NotebookLMClient\n\n    async def main():\n    async with await NotebookLMClient.from_storage() as client:\n    nb = await client.notebooks.create(\"Research\")\n    await client.sources.add_url(nb.id, \"https://arxiv.org/abs/...\")\n    await client.sources.add_file(nb.id, \"./paper.pdf\")\n\n    result = await client.chat.ask(nb.id, \"What are the key findings?\")\n    print(result.answer)# Includes citations\n\n    status = await client.artifacts.generate_audio(nb.id)\n    await client.artifacts.wait_for_completion(nb.id, status.task_id)\n\n    asyncio.run(main())\n\nOr via CLI:\n\n    notebooklm login# Browser auth (one-time)\n    notebooklm create \"My Research\"\n    notebooklm source add ./paper.pdf\n    notebooklm ask \"Summarize the main arguments\"\n    notebooklm generate audio --wait\n\n\\---\n\nInstall:\n\n    pip install notebooklm-py\n\nRepo: [https://github.com/teng-lin/notebooklm-py](https://github.com/teng-lin/notebooklm-py)\n\nWould love feedback on the API design. And if anyone has experience with other batchexecute services (Google Photos, Keep, etc.), I'm curious if the patterns are similar.\n\n\\---"}
{"instruction": "GitHub - raghav4882/TerminallyQuick v4.0: Fast, user-friendly image processing tool [Open Source]", "input": "", "output": "GitHub - raghav4882/TerminallyQuick v4.0: Fast, user-friendly image processing tool [Open Source]\nHello Everyone,\nI am sharing this here because I was exhausted with tools like JPEGmini, Photoshop scripts / Photoshop in general, Smush & other plugins (even though they are great!) being slow on my servers compared to my PC/Mac.\n\nWordpress Designers like me works with many images, Envato Licenses, Subscriptions and ofcourse,;CLIENT DSLR DUMPS (\\*cries in wordpress block\\*)\n\nThis is a MIT Licensed, Self-contained Python tool that has a .bat (batch fil) for Windows and a .command file for Macs that is 100% isolated in its virtual environment of Python. IT doesn't mess with your homebrew installs. it is descriptive and transparent on every step so you know what is exactly happening. I didn't know how much work that would be before I got into it, But it finally came together :') I wanted to make sure User experience was better when you use it rather than the janky UI that only I understood. It installs Pillow and other relevant dependencies automatically.\n\nIt takes the smallest edge for the size, so if you put in 450px (default is 800), whatever image you give it, it will take it and check for smallest edge and make it 450px, and adjusts the other edge proportionally. (Basic options to crop too, default is no, ofcourse).\n\nI had previously created a thread sharing the same when this project was in infancy (v2.0) about 5 months ago. A lot has changed since and alot more is polished. I cleaned the code and made it multithreaded. I humanly cannot write all the features down below because my ADHD doesn't allow me, so please feel free to just visit the Github page and details are right there. I have added Fastrack Profiles so you can save your selections and just fly through your images. There's something called watchdog that does what it says.  A watchdog is something that points to directory you have chosen to paste photos and optimize them when pasted automatically to said config. you stop it and it stops.\n\nMultiple image formats and Quality options (upscaling as well) made it fast for me to work with projects. Such that I don't use plugins anymore to compress images on my server as doing on my system is just plain faster and less painful. Personal choice obviously, Your workflow might differ. Anyways.\n\nThanks for your time reading this.\nHappy New Year everyone! I hope you all land great clients and projects this year."}
{"instruction": "Typed Tailwind/BasecoatUI components for Python&HTMX web apps", "input": "", "output": "Typed Tailwind/BasecoatUI components for Python&HTMX web apps\nHi,\n\n**What my project does**\n\n[htmui](https://github.com/volfpeter/htmui) is a small component library for building Tailwind/shadcn/basecoatui-style web applications 100% in Python\n\nWhat's included:\n\n- all non-trivial [BasecoatUI](https://basecoatui.com/) components\n- [Highlight.js](https://highlightjs.org/) integration\n- a couple of related utilities\n\n**Target audience**:\n\n- you're developing HTMX applications\n- you like TailwindCSS and shadcn/ui or BasecoatUI\n- you'd like to avoid Jinja-like templating engines\n- you'd like even your UI components to be typed and statically analyzed\n- you don't mind HTML in Python\n\n**Documentation and example app**\n\n- URL: https://htmui.vercel.app/\n- Code: see the `basecoat_app` package in the repository (https://github.com/volfpeter/htmui)\n- Backend stack:\n  - [holm](https://volfpeter.github.io/holm/): light FastAPI wrapper with built-in HTML rendering and HTMX support, FastHTML alternative\n  - [htmy](https://volfpeter.github.io/htmy/): async DSL for building web applications (FastHTML/Jinja alternative)\n- Frontend stack: TailwindCSS, BasecoatUI, Highlight.js, HTMX\n\nCredit: this project wouldn't exist if it wasn't for BasecoatUI and its excellent documentation."}
{"instruction": "Pure Python Web Development using Antioch", "input": "", "output": "Pure Python Web Development using Antioch\nOver the last few months I have been creating a Pyodide-based ecosystem for web development called Antioch. It is finally to a place where I think it would benefit from people trying it out.\n\nWhat makes this framework great is the ability to code declaratively and imperatively in the same space, and create/reuse components. You can define elements and macros, add them to the DOM, and control their behavior via event handlers.\n\nMacros are either native Python/Antioch or wrappers integrating existing JS libraries. I've implemented parts of CodeMirror, Leaflet, and Chart.js.\n\nAn example of the most basic features (not including macros):\n\n    from antioch import DOM, Div, H1, Button\n\n    def main():\n\n        # Create elements\n\n        container = Div(\n            H1(\"Hello, Antioch!\",\n                style={\n                    \"color\": \"#2196F3\",\n                    \"background-color\": \"#000000\"\n                }\n            ),\n            P(\"This is a webpage written entirely in Python\")\n        )\n\n        button = Button(\"Click Me\")\n        button.style.padding = \"10px 20px\"\n        button.on_click(\n            lambda e: DOM.add(\n                P(\"You clicked the button!\")\n            )\n        )\n\n        # Add to page\n        container.add(button)\n        DOM.add(container)\n\n    if __name__ == \"__main__\":\n        main()\n\nYou can find the source at [https://github.com/nielrya4/Antioch](https://github.com/nielrya4/Antioch) . Check out the readme, clone the repository, and try it out. Let me know what you think (keep criticism constructive please). I am open to suggestions regarding the direction and content of the project. Thanks for checking it out!\n\nTarget audience: Web developers who love Python\n\nComparison: This is kind of like PyScript, but with a much better structure and ecosystem. Anything you can do in PyScript, you can do more beautifully and rapidly in Antioch"}
{"instruction": "Tutorial: From your first Celery task to advanced recipes", "input": "", "output": "Tutorial: From your first Celery task to advanced recipes\nI wrote a practical guide to Celery, a distributed task queue for Python. It starts with the basics and then covers recipes for timeouts, retries, async/await integration, and more. Most of these recipes came from problems I ran into while using Celery in actual projects. No prior knowledge of Celery is required.\n\nI'd really appreciate any feedback!\n\n[https://sgolev.github.io/blog/[PHONE]-celery-recipes/](https://sgolev.github.io/blog/[PHONE]-celery-recipes/)"}
{"instruction": "AmzPy: An Amazon Scraper born out of API frustration (uses curl_cffi for TLS fingerprinting)", "input": "", "output": "AmzPy: An Amazon Scraper born out of API frustration (uses curl_cffi for TLS fingerprinting)\nWhat My Project Does:\n\n**AmzPy** is a Python library designed to scrape Amazon product details and search results without needing official PA-API access.\n\nIt specifically solves the common \"bot detection\" issue by using `curl_cffi` for browser impersonation. Instead of standard `requests`, it mimics the TLS/JA3 fingerprints of real browsers (Chrome, Safari, Firefox), making it much harder for Amazon to block your requests.\n\n**GitHub:** [https://github.com/theonlyanil/amzpy](https://github.com/theonlyanil/amzpy)\n\n**PyPI:** `pip install amzpy`\n\n# Target Audience\n\nThis is intended for **developers and data researchers** who need to build MVPs, price trackers, or affiliate tools but have been denied Amazon PA-API access or find the official API's limitations too restrictive for early-stage development.\n\n# Comparison\n\n* **Vs. Official PA-API:** Doesn't require manual approval or maintaining a specific sales volume to keep your keys active.\n* **Vs. Scrapy/BeautifulSoup:** Standard scrapers often get hit with CAPTCHAs immediately. AmzPy uses `curl_cffi` to bypass these hurdles natively. PLUS, amzpy handles beautifulsoup stuff well.\n* **Vs. Selenium/Playwright:** AmzPy is much lighter and faster as it doesn't require spinning up a full headless browser instance.\n\n**Basic Usage:**\n\n    from amzpy import AmazonScraper\n\n    scraper = AmazonScraper(country_code=\"in\")\n    products = scraper.search_products(query=\"gaming mouse\", max_pages=1)\n\n    for item in products:\n        print(f\"{item['title']} - {item['price']}\")\n\n\nI’d love to hear your thoughts on my library..."}
{"instruction": "I made a unique game to train your Python skills (GitGuessr)", "input": "", "output": "I made a unique game to train your Python skills (GitGuessr)\nI built [GitGuessr](https://www.gitguessr.com/) as a way to train code reading skills in the AI era (where you're often going to be critically reviewing lots of code spat out by your favorite LLM - I mean I sincerely hope you're reviewing the code).\n\nYou're dropped into a random location in a real Python repo on GitHub where some lines of code are hidden. Your goal is to understand the codebase and fill in the missing code as quickly as possible.\n\nUse these links to play games with curated Python repos:\n\n* Easy Python (answer often obvious from immediate context): [https://www.gitguessr.com/map/Z4cWBg03Pk0Y9z-UwZ-In](https://www.gitguessr.com/map/Z4cWBg03Pk0Y9z-UwZ-In)\n* Intermediate Python (harder, may require more browsing of code): [https://www.gitguessr.com/map/UkS41aHemtcxhGGQfdC-S](https://www.gitguessr.com/map/UkS41aHemtcxhGGQfdC-S)\n\nAny feedback on the game welcome btw!"}
{"instruction": "KORE: A new systems language with Python syntax, Actor concurrency, and LLVM/SPIR-V output", "input": "", "output": "KORE: A new systems language with Python syntax, Actor concurrency, and LLVM/SPIR-V output\n# [kore-lang](https://github.com/ephemara/kore-lang)\n\n**What My Project Does** KORE is a self-hosting, universal programming language designed to collapse the entire software stack. It spans from low-level systems programming (no GC, direct memory control) up to high-level full-stack web development. It natively supports JSX/UI components, database ORMs, and Actor-based concurrency without needing external frameworks or build tools. It compiles to LLVM native, WASM, SPIR-V (shaders), and transpiles to Rust.\n\n**Target Audience** Developers tired of the \"glue code\" era. It is for systems engineers who need performance, but also for full-stack web developers who want React-style UI, GraphQL, and backend logic in a single type-safe language without the JavaScript/npm ecosystem chaos.\n\n**Comparison**\n\n* **vs TypeScript/React:** KORE has native JSX, hooks, and state management built directly into the language syntax. No `npm install`, no Webpack, no distinct build step.\n* **vs Go/Erlang:** Uses the Actor model for concurrency (perfect for WebSockets/Networking) but combines it with Rust-like memory safety.\n* **vs Rust:** Offers the same ownership/borrowing guarantees but with Python's clean whitespace syntax and less ceremony.\n* **vs SQL/ORMs:** Database models and query builders are first-class citizens, allowing type-safe queries without reflection or external tools.\n\n# What is KORE?\n\nKORE is a **self-hosting programming language** that combines the best ideas from multiple paradigms:\n\n|**Paradigm**|**Inspiration**|**KORE Implementation**|\n|:-|:-|:-|\n|**Safety**|Rust|Ownership, borrowing, no null, no data races|\n|**Syntax**|Python|Significant whitespace, minimal ceremony|\n|**UI/Web**|React|Native JSX, Hooks (`use_state`), Virtual DOM|\n|**Concurrency**|Erlang|Actor model, message passing, supervision trees|\n|**Data**|GraphQL/SQL|Built-in ORM patterns and schema definition|\n|**Compile-Time**|Zig|`comptime` execution, hygienic macros|\n|**Targets**|Universal|WASM, LLVM Native, SPIR-V, Rust|\n\n    // 1. Define Data Model (ORM)\n    let User = model! {\n    table \"users\"\n    field id: Int\n    field name: String\n    }\n    // 2. Define Backend Actor\n    actor Server:\n    on GetUser(id: Int) -> Option<User>:\n    return await db.users.find(id)\n    // 3. Define UI Component (Native JSX)\n    fn UserProfile(id: Int) -> Component:\n    let (user, set_user) = use_state(None)\n    use_effect(fn():\n    let u = await Server.ask(GetUser(id))\n    set_user(u)\n    , [id])\n    return match user:\n    Some(u) => <div class=\"profile\"><h1>{u.name}</h1></div>\n    None    => <Spinner />"}
{"instruction": "Mesa 4.0 alpha released", "input": "", "output": "Mesa 4.0 alpha released\nHi everyone!\n\nWe've started development towards Mesa 4.0 and just released the first alpha. This is a big architectural step forward: Mesa is moving from step-based to event-driven simulation at its core, while cleaning up years of accumulated API cruft.\n\n* [https://github.com/projectmesa/mesa/releases/tag/v4.0.0a0](https://github.com/projectmesa/mesa/releases/tag/v4.0.0a0)\n\n# What's Agent-Based Modeling?\n\nEver wondered how bird flocks organize themselves? Or how traffic jams form? Agent-based modeling (ABM) lets you simulate these complex systems by defining simple rules for individual \"agents\" (birds, cars, people, etc.) and watching how patterns emerge from their interactions. Instead of writing equations for the whole system, you model each agent's behavior and let the collective dynamics arise naturally.\n\n# What's Mesa?\n\nMesa is Python's leading framework for agent-based modeling. It builds on Python's scientific stack (NumPy, pandas, Matplotlib) and provides specialized tools for spatial relationships, agent scheduling, data collection, and browser-based visualization. Whether you're studying epidemic spread, market dynamics, or ecological systems, Mesa gives you the building blocks for sophisticated simulations.\n\n# What's new in Mesa 4.0 alpha?\n\n**Event-driven at the core.** Mesa 3.5 introduced public event scheduling on `Model`, with methods like `model.run_for()`, `model.run_until()`, `model.schedule_event()`, and `model.schedule_recurring()`. Mesa 4.0 continues development on this front: `model.steps` is gone, replaced by `model.time` as the universal clock. The mental model moves from \"execute step N\" to \"advance time, and whatever is scheduled will run.\" The event system now supports pausing/resuming recurring events, exposes next scheduled times, and enforces that time actually moves forward.\n\n**Experimental timed actions.** A new `Action` system gives agents a built-in concept of doing something over time. Actions integrate with the event scheduler, support interruption with progress tracking, and can be resumed:\n\n    from mesa.experimental.actions import Action\n\n    class Forage(Action):\n        def __init__(self, sheep):\n            super().__init__(sheep, duration=5.0)\n\n        def on_complete(self):\n            self.agent.energy += 30\n\n        def on_interrupt(self, progress):\n            self.agent.energy += 30 * progress  # Partial credit\n\n    sheep.start_action(Forage(sheep))\n\n**Deprecated APIs removed.** This is a major version, so we followed through on removals: the `seed` parameter (use `rng`), `batch_run` (use `Scenario`), the legacy [`mesa.space`](http://mesa.space) module (use `mesa.discrete_space`), `PropertyLayer` (replaced by raw NumPy arrays on the grid), and the `Simulator` classes (replaced by the model-level scheduling methods). If you've been following deprecation warnings in 3.x, most of this should be straightforward.\n\n**Cleaner internals.** A new `mesa.errors` exception hierarchy replaces generic `Exception` usage. `DiscreteSpace` is now an abstract base class enforcing a consistent spatial API. Property access on cells uses native property closures on a dynamic `GridCell` class. Several targeted performance optimizations reduce allocations in the event system and continuous space.\n\n# This is an alpha\n\nExpect rough edges. We're releasing early to get feedback from the community before the stable release. Further breaking changes are possible. If you're runnin"}
{"instruction": "PEP 842: Module Exports", "input": "", "output": "PEP 842: Module Exports\nhttps://discuss.python.org/t/pep-842-module-exports/108353\n\nNot the author, but this seems interesting, specially for library authors. Thoughts?"}
{"instruction": "Parameterize a Fixture instead of a Test Case with Pytest", "input": "", "output": "Parameterize a Fixture instead of a Test Case with Pytest\nI 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.\n\n[https://www.visualmode.dev/parameterize-a-fixture-instead-of-a-test-case-with-pytest](https://www.visualmode.dev/parameterize-a-fixture-instead-of-a-test-case-with-pytest)\n\nTo 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."}
{"instruction": "Code In Place 2026", "input": "", "output": "Code In Place 2026\nThe popular and international code in place Python learning course from Stanford now open for 2026 applications.\n\nhttp://codeinplace.stanford.edu/apply/cipx/student?r=d2lx8w\n\nSee you there."}
{"instruction": "pdftotext -layout still isn't enough when a government PDF is secretly a 3-column table", "input": "", "output": "pdftotext -layout still isn't enough when a government PDF is secretly a 3-column table\nWorking through an old government safety document today and the raw text order was completely scrambled, hazard descriptions and countermeasures kept interleaving mid sentence. Turned out the whole page is a 3-column table, and if you don't slice by column x-position it just reads left to right across the whole line like it's one paragraph.\n\n\nFixed that with -layout and cutting at the column boundaries, but then hit a dumber problem: some lines have two □ markers on them, one for the subcategory heading and one for the first hazard item. Grab the first □ naively and the subcategory swallows the whole first hazard entry, and you don't notice until you're 40 rows in and something reads wrong.\n\n\nAlso found two pages where a single set of countermeasures gets shared by two different subcategories, which nothing in the text structure hints at, you just have to know the source document does that."}
{"instruction": "I really enjoy Python compared to other coding I've done", "input": "", "output": "I really enjoy Python compared to other coding I've done\nI've been using Python for a while now and it's my main language. It is such a wonderful language. Guido had wonderful design choices in forcing whitespace to disallow curly braces and discouraging semicolons so much I almost didn't know they existed. There's even a synonym for beautiful; it's called *pythonic*.\n\nI will probably not use the absolute elephant dung that is NodeJS ever again. Everything that JavaScript has is in Python, but better. And whatever exists in JS but not Python is because it didn't need to exist in Python because it's unnecessary. For example, Flask is like Express but better. I'm not stuck in callback hell or dependency hell.\n\nThe only cross-device difference I've faced is sys.exit working on Linux but not working on Windows. But in web development, you gotta face vendor prefixes, CSS resets, graceful degradation, some browsers not implementing standards right, etc. Somehow, Python is more cross platform than the web is. Hell, Python even runs on the web.\n\nI still love web development though, but writing Python code is just the pinnacle of wonderful computer experiences. This is the same language where you can make a website, a programming language, a video game (3d or 2d), a web scraper, a GUI, etc.\n\nWhenever I find myself limited, it is never implementation-wise. It's never because there aren't enough functions. I'm only limited by my (temporary) lack of ideas. Python makes me love programming more than I already did.\n\nBut C, oh, C is cool but a bit limiting IMO because all the higher level stuff you take for granted like lists and whatever aren't there, and that wastes your time and kind of limits what you can do. C++ kinda solves this with the <vector> module but it is still a hassle implementing stuff compared to Python, where it's very simple to just define a list like \\[1,2,3\\] where you can easily add more elements without needing a fixed size.\n\nThe C and C++ language's limitations make me heavily appreciate what Python does, especially as it is coded in C."}
{"instruction": "Python Script Ranking All 262,143 Possible Pokemon Type Combinations", "input": "", "output": "Python Script Ranking All 262,143 Possible Pokemon Type Combinations\n**What My Project Does:** Finds all possible combinations of Pokemon types from 1 type to 18 types, making 262,143 combinations in total, and scores their offensive and defensive capabilities.\n\n**Target Audience:** Anyone who plays Pokemon! This is just for fun.\n\n**Comparison:** Existing rankings only rank combinations possible in the game (1 type or 2 types) but this analyzes the capabilities of type combinations that couldn't normally exist in-game (3 types to 18 types).\n\n\\-----------------------------------------------------------------------------------------------------\n\nI wrote a Python script with Pandas and Multiprocessing that analyzes all possible Pokemon type combinations and ranks them according to their offensive and defensive capabilities. It doesn't just do 1-2 types, but instead all combinations up to 18 types. This makes for 262,143 possible combinations in total!\n\n\n**Some highlights:**\n\nThe best possible defensive combination is:\n\n    ['Normal', 'Fire', 'Water', 'Electric', 'Poison', 'Ground', 'Flying', 'Ghost', 'Dragon', 'Dark', 'Steel', 'Fairy']\n\nThis has no weaknesses.\nResists Fire, Grass, Flying, Bug (0.03125x damage lol), Dark, Steel, and Fairy.\nImmune to Normal,\tElectric, Fighting, Poison, Ground, Psychic, and Ghost.\nThis ranked 28th overall.\n\nThat's only 12 types though. If a Pokemon had all 18 types, a.k.a:\n\n    ['Normal', 'Fire', 'Water', 'Electric', 'Grass', 'Ice', 'Fighting', 'Poison', 'Ground', 'Flying', 'Psychic', 'Bug', 'Rock', 'Ghost', 'Dragon', 'Dark', 'Steel', 'Fairy']\n\n\nIt would be weak to only Rock, but it would only resist Grass, Bug, Dark, and Steel.\nThis ranked 1,992nd place in defense and 536th overall.\n\nThe smallest number of types to hit all Pokemon for super effective STAB is 7. There were 10 7-type combinations that could hit all types for super effective damage. In total, 16,446 combinations could do this.\n\nThe single worst defensive type combination is:\n\n    ['Grass', 'Ice', 'Psychic', 'Bug', 'Dragon']\n\nIts weaknesses are\n\n    Fire: 4.0x\n    Ice: 2.0x\n    Poison: 2.0x\n    Flying: 4.0x\n    Bug: 4.0x\n    Rock: 4.0x\n    Ghost: 2.0x\n    Dragon: 2.0x\n    Dark: 2.0x\n    Steel: 2.0x\n    Fairy: 2.0x\n\nOuch. This combination placed 262,083rd overall.\n\nAnd the single lowest-scored type combination out of all 262,143 is... *Grass*. That's it. Pure Grass.\n\n**Looking at only 1-type and 2-type combinations:**\n\nTop 5 by Offense:\n\n    Rank 1:   ['Ice', 'Ground']        75.0%  Highest for 2 types.\n    Rank 2:   ['Ice', 'Fighting']      75.0%  Highest for 2 types.\n    Rank 3:   ['Ground', 'Flying']     72.22%\n    Rank 4:   ['Fire', 'Ground']       72.22%\n    Rank 5:   ['Ground', 'Fairy']      72.22%\n\nTop 5 by Defense:\n\n    Rank 1:   ['Flying', 'Steel']      69.44% Highest for 2 types.\n    Rank 2:   ['Steel', 'Fairy']       69.44% Highest for 2 types.\n    Rank 3:   ['Normal', 'Ghost']      68.06%\n    Rank 4:   ['Bug', 'Steel']         67.36%\n    Rank 5:   ['Ghost', 'Steel']       67.36%\n\nTop 5 Overall:\n\n    Rank 1:\n    ['Ground', 'Flying']\n    # of Types: 2\n    Offense Score: 72.22%\n    Defense Score: 63.19%\n    Overall:       67.71% Highest average for 2 types.\n\n    Rank 2:\n    ['Fire', 'Ground']\n    # of Types: 2\n    Offense Score: 72.22%\n    Defense Score: 62.5%\n    Overall:       67.36%\n\n    Rank 3:\n    ['Ground', 'Steel']\n    # of Types: 2\n    Offense Score: 69.44%\n    Defense Score: 64.58%\n    Overall:"}
{"instruction": "zipinspect - inspect/extract zip files over HTTP, blazingly fast!", "input": "", "output": "zipinspect - inspect/extract zip files over HTTP, blazingly fast!\n[Github](https://github.com/cynthia2006/zipinspect).\n\n# What My Project Does\n\nSometimes we only need a one or two files from a large remotely located Zip file, but there's generally no Zip utility that could handle this usecase without downloading the whole Zip file. Say, if you need a few hundred pictures (worth 20 MiB) from a remote Zip file weighing 3-4 GiBs, would it be worth downloading the whole archive? Ofcourse not. Not everyone has high-bandwith network connections or enough time to wait for the entire archive to finish downloading.\n\nThis tool comes to rescue in such situations. Sounds all too abstract? Here's a small demo.\n\n    $ zipinspect 'https://example.com/ArthurRimbaud-OnlyFans.zip'\n    > list\n      #  entry                    size    modified date\n    ---  -----------------------  ------  -------------------\n      0  ArthurRimbaudOF_001.jpg  2.2M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_002.jpg  2.4M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_003.jpg  2.4M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_004.jpg  2.5M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_005.jpg  2.3M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_006.jpg  2.4M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_007.jpg  2.2M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_008.jpg  2.4M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_009.jpg  2.4M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_010.jpg  2.3M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_011.jpg  2.5M    2024-11-07T18:41:[PHONE]  ArthurRimbaudOF_012.jpg  1.5M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_013.jpg  2.4M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_014.jpg  2.6M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_015.jpg  2.8M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_016.jpg  2.8M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_017.jpg  2.3M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_018.jpg  2.9M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_019.jpg  3.1M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_020.jpg  2.9M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_021.jpg  3.1M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_022.jpg  3.1M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_023.jpg  3.1M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_024.jpg  3.0M    2024-11-07T18:42:[PHONE]  ArthurRimbaudOF_025.jpg  2.9M    2024-11-07T18:42:14\n    (Page 1/14)\n    > extract 8\n\n     |#######################################################################| 100%\n\n    > extract 8,9,16\n\n     |#######################################################################| 100%\n\n    > extract 20,...,24\n\n     |#######################################################################| 100%\n\n    >\n\nThis is would download the pictures in the current directory. By the way, it downloads multiple files in parallel thanks to asyncio — blazingly fast!\n\n# Target Audience\n\nThose who love doing things the most efficient way possible — nitpicky ones like me.\n\n# Comparison\n\nMost libraries dealing with Zip files aren't HTTP-aware (including zipfile in the standard library), thus most tools are unable to deal with remote Zip files, or can't do so efficiently. To cater to its unique usecase, this tool contains an in-house HTTP-aware Zip (and Zip64) implementation based on the original PKWare APPNOTE.txt and Wikipedia."}
{"instruction": "Implementing OpenTelemetry in FastAPI Projects", "input": "", "output": "Implementing OpenTelemetry in FastAPI Projects\nHi Pythonistas, I recently revamped our article on [Implementing OpenTelemetry in FastAPI Projects](https://signoz.io/blog/opentelemetry-fastapi/) in a practical manner, which was originally written in 2024 and needed a fresh coat of paint.\n\nThe article covers auto-instrumentation, manual spans, visualizing metrics and how observability lets you understand how your web apps behave.\nI've also included some advanced tips, such as, selective error tracking, and wrapping dependency functions to capture any operations within the \\`yield\\` scope.\n\nSince a lot of the concepts discussed here are independent of the FastAPI framework, any developer working with Python can probably find something of use here.\n\nFinally, I hope this write up helps some folks become familiar with OpenTelemetry and observability.\nAny feedback would be much appreciated, also curious to understand what problems you face with monitoring your web apps, be it FastAPI or any other web framework.\n\n\\---\n\nOn a personal note, when implementing OpenTelemetry in my previous job, I went in semi-blind and relied on agents to guide me, and then spend a good week dealing with the various issues that popped up along the way..."}
{"instruction": "Are there any python modules that automatically generated a requirements.txt, given an entry point?", "input": "", "output": "Are there any python modules that automatically generated a requirements.txt, given an entry point?\nI know things like pipreqs exist, but that's more of an directory scan. If you have a project and you need several requirements.txts (for multiple containers / multiple entrypoints), I haven't found a way to reliably generate that. Please let me know if things like this do exist, because if not I'd really like to make my own module to do this stuff. And if there is something like that, it would really come in handy for me right now."}
{"instruction": "LANscape - A python based local network scanner", "input": "", "output": "LANscape - A python based local network scanner\nI wanted to show off one of my personal projects that I have been working on for the past few years now, it's called LANscape & it's a full featured local network scanner with a react UI bundled within the python library.\n\n[https://github.com/mdennis281/LANscape](https://github.com/mdennis281/LANscape)\n\n**What it does:**\n\nIt uses a combination of ARP / TCP / ICMP to determine if a host exists & also executes a series of tests on ports to determine what service is running on them. This process can either be done within LANscape's module-based UI. or can be done importing the library in python.\n\n**Target audience:**\n\nIt's built for anyone who wants to gain insights into what devices are running on their network.\n\n**Comparison** :\n\nThe initial creation of this project stemmed from my annoyance with a different software, \"Advanced IP Scanner\" for it's general slowness and lack of configurable scanning parameters. I built this new tool to provide deeper insights into what is actually going on in your network.\n\nIt's some of my best work in terms of code quality & I'm pretty proud of what's its grown into.\nIt's pip installable by anyone who wants to try it & works completely offline.\n\n    pip install lanscape\n    python -m lanscape"}
{"instruction": "Notebook.link: Create, share, and run Jupyter notebooks instantly in your browser!", "input": "", "output": "Notebook.link: Create, share, and run Jupyter notebooks instantly in your browser!\nBuilt on JupyterLite, [notebook.link](http://notebook.link) is more than just a notebook viewer: it’s a fully **interactive**, **scalable**, and **language-agnostic** computing environment that operates entirely in your browser. Whether you’re a data scientist, educator, researcher, or developer, [notebook.link](http://notebook.link) eliminates the need for local installations or complex setups, allowing you to create, share, and execute notebooks effortlessly."}
{"instruction": "Python brought me joy back on building web apps", "input": "", "output": "Python brought me joy back on building web apps\nI have been a multi-language experienced dev for the longest time and always had this restriction with python because of lack of brackets. Lets face it, it is an acquired taste. After a year working with Python my joy of building we apps is back something that I had somewhat lost with my long good friend PHP. I'm not going to fully switch. Never done that before will never do that now. For me languages is a tool, nothing more than that, but is good to be using a tool that brings you joy every now and then."}
{"instruction": "I built a small CLI tool to convert relative imports to absolute imports during a large refactoring", "input": "", "output": "I built a small CLI tool to convert relative imports to absolute imports during a large refactoring\nWhile refactoring a large Python project, I ran into an issue — the project had a lot of deeply nested relative imports (from ..module import x). The team decided to standardize everything to absolute imports, and here was the issue: manually updating them was very tedious, especially across many levels of relative imports.\nSo I wrote a small CLI tool that:\n- Traverses the project directory\n- Detects relative imports\n- Converts them to absolute imports based on a given root package\nIt’s lightweight and dependency-free. Nothing fancy — just a utility that solved a real problem for me and I thought it might be useful for some people.\nIf anyone is going through a similar refactor, feel free to check it out on github:\n[github](https://github.com/SamiJneidy/relative2absolute)\nand you can install it using pip also.\nI know it's very minimal, but I would appreciate feedback or suggestions."}
{"instruction": "Skylos: Python SAST, Dead Code Detection & Security Auditor (Benchmark against Vulture)", "input": "", "output": "Skylos: Python SAST, Dead Code Detection & Security Auditor (Benchmark against Vulture)\nHey! I was here a couple of days back, but I just wanted to update that we have created a benchmark against vulture and fixed some logic to reduce false positives.  For the uninitiated, is a local first static analysis tool for Python codebases. **If you've already read this skip to the bottom where the benchmark link is.**\n\n# What my project does\n\nSkylos focuses on the stuff below:\n\n* dead code (unused functions/classes/imports. The cli will display confidence scoring)\n* security patterns (taint-flow style checks, secrets, hallucination etc)\n* quality checks (complexity, nesting, function size, etc.)\n* pytest hygiene (unused [u/pytest](https://www.reddit.com/user/pytest/).fixtures etc.)\n* agentic feedback (uses a hybrid of static + agent analysis to reduce false positives)\n* `--trace` to catch dynamic code\n\n# Quick start (how to use)\n\nInstall:\n\n`pip install skylos`\n\nRun a basic scan (which is essentially just dead code):\n\n`skylos .`\n\nRun sec + secrets + quality:\n\n`skylos . --secrets --danger --quality`\n\nUses runtime tracing to reduce dynamic FPs:\n\n`skylos . --trace`\n\nGate your repo in CI:\n\n`skylos . --danger --gate --strict`\n\nTo use [skylos.dev](http://skylos.dev/) and upload a report. You will be prompted for an api key etc.\n\n`skylos . --danger --upload`\n\n# VS Code Extension\n\nI also made a **VS Code extension** so you can see findings in-editor.\n\n* Marketplace: You can search it in your VSC market place or via oha.skylos-vscode-extension\n* It runs the CLI on save for static checks\n* Optional AI actions if you configure a provider key\n\n# Target Audience\n\nEveryone working on python\n\n# Comparison (UPDATED)\n\nOur closest comparison will be vulture. We have a benchmark which we created. We tried to make it as realistic as possible, trying to mimic what a lightweight repo might look like. We will be expanding the benchmark to include monorepos and a much heavier benchmark. The logic and explanation behind the benchmark can be found here. The link to the document is here [https://github.com/duriantaco/skylos/blob/main/BENCHMARK.md](https://github.com/duriantaco/skylos/blob/main/BENCHMARK.md) and the actual repo is here [https://github.com/duriantaco/skylos-demo](https://github.com/duriantaco/skylos-demo)\n\n# Links / where to follow up\n\n* Website: [https://skylos.dev](https://skylos.dev/)\n* Discord (support/bugs/features request): [https://discord.gg/Ftn9t9tErf](https://discord.gg/Ftn9t9tErf)\n* Repo: [https://github.com/duriantaco/skylos](https://github.com/duriantaco/skylos)\n* Docs: [https://docs.skylos.dev/](https://docs.skylos.dev/)\n\nHappy to take any constructive criticism/feedback. We do take all your feedback seriously and will continue to improve our engine. The reason why we have not expanded into other languages is because we're trying to make sure we reduce false positives as much as possible and we can only do it with your help.\n\nWe'd love for you to try out the stuff above. If you try it and it breaks or is annoying, let us know via discord. We recently created the discord channel for more real time feedback. We will also be launching a \"False Positive Hunt Event\" which will be on [https://skylos.dev](https://skylos.dev) so if you're keen to take part, let us know via discord!  **And give it a star if you found it useful.**\n\n**Last but not least, if you'll like your repo cleaned, do drop us a discord or email us at** [**[EMAIL]**](m"}
{"instruction": "Learn NumPy indexing with our little game: NumPy Ducky", "input": "", "output": "Learn NumPy indexing with our little game: NumPy Ducky\nNumPy Ducky is a game that helps beginners learn basics of NumPy indexing by helping ducks get into water, inspired by the legendary Flexbox Froggy.\n\n**Repo:** [https://github.com/0stam/numpy-ducky](https://github.com/0stam/numpy-ducky)\n**Download:** [https://github.com/0stam/numpy-ducky/releases](https://github.com/0stam/numpy-ducky/releases)\n\n**What My Project Does**\n\nIt allows you to see visual results of your code, which should make it easier to grasp indexing and dimensionality up to 3D.\n\nEach level contains ducks sitting on a 1-3D array. Your goal is to put a pool of water under them. As you type the indexing code, the pool changes it's position, so that you can understand and correct your mistakes.\n\n**Target Audience**\n\nBeginners wanting to understand NumPy indexing and dimensionality, especially for the purpose of working with ML/image data.\n\n**Comparison**\n\nI haven't seen any similar NumPy games. The project heavily inspired by Flexbox Froggy, which provides a similar game for understanding CSS Flexbox parameters.\n\nThe game was made as a university project. The scope is not huge, but I hope it's helpful."}
{"instruction": "Detecting sync code blocking asyncio event loop (with stack traces)", "input": "", "output": "Detecting sync code blocking asyncio event loop (with stack traces)\nSync code hiding inside \\`async def\\` functions blocks the entire event loop - boto3, requests, fitz, and many more libraries do this silently.\n\nBuilt a tool that detects when the event loop is blocked and gives you the exact stack trace showing where. Wrote up how it works with a FastAPI example - PDF ingestion service that extracts text/images and uploads to S3.\n\nResults from load testing the blocking vs async version:\n\n* 100 concurrent requests: +31% throughput, -24% p99 latency\n* 1000 concurrent requests: +36% throughput, -27% p99 latency\n\n[https://deepankarm.github.io/posts/detecting-event-loop-blocking-in-asyncio/](https://deepankarm.github.io/posts/detecting-event-loop-blocking-in-asyncio/)\n\nLibrary: [https://github.com/deepankarm/pyleak](https://github.com/deepankarm/pyleak)"}
{"instruction": "Unopposed - Track Elections Without Opposition", "input": "", "output": "Unopposed - Track Elections Without Opposition\n[Source: Python Scraper](https://github.com/danpozmanter/unopposed/tree/main/scraper)\n\n[Visualization Link](https://danpozmanter.github.io/unopposed/)\n\n**What it Does**\n\nScrapes Ballotpedia for US House & Senate races, and State House, Senate, and Governor races to look for primaries and general elections where candidates are running (or ran) without opposition.\n\n**Target Audience**\n\nAnyone in the US who wants to get more involved in politics, or look at politics through the lens of data. It's meant as a tool (or an inspiration for a better tool). Please feel free to fork this project and take it in your own direction.\n\n**Comparison**\n\nI found this [270towin: Uncontested races](https://www.270towin.com/2024-house-election-uncontested-races/), and of course there's my source for the data, Ballotpedia. But I didn't find a central repository of this data I could pull, see at a glance, dig into, or analyze. If there is an alternative please do post it - I'm much more interested in the data than I am in having built something to get the data. (Though it was fun to build).\n\n**Notes**\n\nMy motivation for writing this was to get a sense of who was running without opposition, when I saw my own US Rep was entirely unopposed (no primary or general challengers as of yet).\n\nThis could be expanded to pull from other sources, but I wanted to start here.\n\nWritten primarily in Python, but has a frontend using Typescript and Svelte. Uses github actions to run the scraper once a day. This was my first time using Svelte."}
{"instruction": "CytoScnPy: Python Dead Code Detection", "input": "", "output": "CytoScnPy: Python Dead Code Detection\n# What My Project Does\n\n**CytoScnPy** is a practical static analysis tool for Python that focuses on identifying **dead code**, **basic security risks**, and **simple code quality metrics**—without heavy configuration or long scan times.\n\nIt’s designed to work well even on large codebases and to be usable both locally and in CI environments.\n\n**Key features:**\n\n* **Dead Code Hunt:** Detects unused imports, methods, variables (with preview & auto-fix)\n* **Security Scan:** Secret detection and basic taint tracking (e.g., `eval()`\\-style risks)\n* **Quality Check:** Cyclomatic complexity, Halstead metrics, maintainability scores\n* **Clone Spotter:** Finds duplicated or structurally similar code\n* **MCP Server & VS Code Extension**\n* **Integrations:** JSON reports for CI pipelines and AI tooling hooks\n\n# Target Audience\n\nCytoScnPy is intended for:\n\n* **Developers and small teams** who want fast feedback without heavyweight tooling\n* **CI users** who want dead-code and basic security signals as part of automation\n* **Side projects, startups, and internal tools**, rather than enterprise-grade compliance scanning\n\nIt’s not meant to replace full SAST platforms, but to be a **lightweight, practical analyzer** you can run often.\n\n# Comparison with Existing Tools\n\nCompared to popular Python tools:\n\n* **vs. pylint / flake8:** CytoScnPy focuses more on *actual dead code* and structural analysis rather than style rules.\n* **vs. bandit:** Security checks are intentionally simpler and faster, aimed at early risk detection rather than exhaustive audits.\n* **vs. radon:** Includes similar complexity metrics, but combines them with dead-code detection and clone spotting in one pass.\n* **vs. large SAST tools:** Much faster, fewer false positives, and easier to integrate—but with a narrower scope by design.\n\n# Links\n\n* **Docs:** [https://djinn-soul.github.io/CytoScnPy/](https://djinn-soul.github.io/CytoScnPy/)\n* **GitHub:** [https://github.com/djinn-soul/CytoScnPy](https://github.com/djinn-soul/CytoScnPy)\n* **VS Code Extension:** [https://marketplace.visualstudio.com/items?itemName=djinn09.cytoscnpy](https://marketplace.visualstudio.com/items?itemName=djinn09.cytoscnpy)\n\nPlease give it a try and share your thoughts—features, bugs, or general feedback are all welcome."}
{"instruction": "How much meaning do you encode into names before they become too long?", "input": "", "output": "How much meaning do you encode into names before they become too long?\nI am super curious what naming rules do you use in Python?\n\nDo you standardize things like:\n\n\\- suffixes / prefixes (DTO, Service, Manager, etc.)\n\n\\- naming length (short vs explicit)\n\n\\- abstraction levels in names\n\nOr does it change per project?\n\nFor me, **naming is everything**.\n\nIf I see the name - I should know precisely what it does without guesses.\n\nI often rename the same thing 5–10 times until it “sits” and feels stable.\n\nSometimes the name becomes painfully long, but you know exactly what it does:\n\nI just grepped the longest name in codebase\n\n    class AssertRepeatedRequestNonBytePayloadMatches: ...\n\n\nAt what point do you stop adding meaning and accept ambiguity?"}
{"instruction": "LLVMLite and first step to get Numba in the browser", "input": "", "output": "LLVMLite and first step to get Numba in the browser\nHi,\n\nAnutosh Bhat, a colleague of mine, just posted this on Linkedin:\n\n>What if real compiler infrastructures could run entirely inside the browser?\n>\n>I’ve successfully patched llvmlite for JupyterLite, making it possible to build >LLVM IR, run optimization passes, visualize control-flow graphs, compile to >WebAssembly and execute the result — without a native LLVM setup or server-side >kernel.\n>\n>I’ve shared a step-by-step notebook showing how a loop evolves from stack-based IR >to SSA, then to an LICM-style form, into a fully optimized closed form, eventually >to benchmark all of these steps.\n>\n>The bigger idea is a zero-install compiler workbench for reproducible optimization >experiments, lightweight compiler prototyping, IR debugging, custom code->generation pipelines, shareable research demos, and eventually interactive >tutorials and compiler courses.\n>\n>Try out the interactive notebook using notebook.link: [**https://notebook.link/@anutosh491/llvmlite**](https://notebook.link/@anutosh491/llvmlite)\n>\n>I’m also in the process of bringing MLIR Python bindings into the same JupyterLite >and WebAssembly environment, starting with a 2D CNN-style Conv2D + bias + ReLU >kernel. I’ll share the full pipeline in a separate technical blog post soon.\n>\n>I’ve also started patching Numba for Wasm and have simple scalar u / jit functions >running inside JupyterLite. Array and tensor workloads are the next challenge.\n>\n>I’m keen to take this further. If you’re working on LLVM, MLIR, Numba, WebAssembly >or browser-native developer tools — or see a real use case for this — I’d be >interested in connecting with teams looking to collaborate, support the work or >explore what we could build together.\n\nNext step is to patch Numba to get scalar jit !: [https://www.linkedin.com/feed/update/urn:li:ugcPost:7485014172934541312/?dashCommentUrn=urn%3Ali%3Afsd\\_comment%3A%287485014751178211329%2Curn%3Ali%3AugcPost%3A7485014172934541312%29](https://www.linkedin.com/feed/update/urn:li:ugcPost:7485014172934541312/?dashCommentUrn=urn%3Ali%3Afsd_comment%3A%287485014751178211329%2Curn%3Ali%3AugcPost%3A7485014172934541312%29)"}
{"instruction": "Compute! - Open-source and Data Science conference - Paris - November 2026", "input": "", "output": "Compute! - Open-source and Data Science conference - Paris - November 2026\nIf you care about open-source tools for data, ML/AI, and scientific computing, Compute! Paris 2026 has a [very strong talk lineup](https://compute.events/paris2026/schedule.html).\n\nThere is many presentations: Jupyter, scikit-learn, numpy, Arrow, visualization, in-browser computing, etc ...\n\nI  give a talk about [Sparrow](https://github.com/sparrow-org/sparrow) (C++20 implementation for Apache Arrow with mutable arrays).\n\nThere are also **f**ree sprints on Nov 27 where you can contribute directly to the projects behind many of these talks.\n\nYou can check it here: [https://compute.events/paris2026/index.html](https://compute.events/paris2026/index.html)"}
{"instruction": "Large simulation performance: objects vs matrices", "input": "", "output": "Large simulation performance: objects vs matrices\nHi!\n\nLet’s say you have a simulation of 100,000 entities for X time periods.\n\nThese entities do not interact with each other. They all have some defined properties such as:\n\n1. Revenue\n\n2. Expenditure\n\n3. Size\n\n4. Location\n\n5. Industry\n\n6. Current cash levels\n\nFor each increment in the time period, each entity will:\n\n1. Generate revenue\n\n2. Spend money\n\nAt the end of each time period, the simulation will update its parameters and check and retrieve:\n\n1. The current cash levels of the business\n\n2. If the business cash levels are less than 0\n\n3. If the business cash levels are less than it’s expenditure\n\nIf I had a matrix equation that would go through each step for all 100,000 entities at once (by storing the parameters in each matrix) vs creating 100,000 entity objects with aforementioned requirements, would there be a significant difference in performance?\n\nThe entity object method makes it significantly easier to understand and explain, but I’m concerned about not being able to run large simulations."}
{"instruction": "Grantflow.AI codebase is now public", "input": "", "output": "Grantflow.AI codebase is now public\nHi peeps,\n\nAs I wrote in the title. I and my cofounders decided to open https://grantflow.ai as source-available (BSL) and make the repo public. Why? well, we didn't manage to get sufficient traction in our former strategy, so we decided to pivot. Additionally, I had some of my mentees helping with the development (junior devs), and its good for their GitHub profiles to have this available.\n\nYou can see the codebase here: https://github.com/grantflow-ai/grantflow -- I worked on this extensively for the better part of a year. This features a complex and high performance RAG system with the following components:\n\n1. An `indexer` service, which uses [kreuzberg](https://github.com/kreuzberg-dev/kreuzberg) for text extraction.\n2. A `crawler` service, which does the same but for URLs.\n3. A `rag` service, which uses pgvector and a bunch of ML to perform sophisticated RAG.\n4. A `backend` service, which is the backend for the frontend.\n5. Several frontend app components, including a NextJS app and an editor based on TipTap.\n\nI am proud of this codebase - I wrote most of it, and while we did use AI agents, it started out by being hand-written and its still mostly human written. It show cases various things that can bring value to you guys:\n\n1. how to integrate SQLAlchemy with pgvector for effective RAG\n2. how to create evaluation layers and feedback loops\n3. usage of various Python libraries with correct async patterns (also ML in async context)\n4. usage of the Litestar framework in production\n5. how to create an effective uv + pnpm monorepo\n6. advanced GitHub workflows and integration with terraform\n\nI'm glad to answer questions.\n\nP.S. if you wanna chat with me on discord, I am on the [Kreuzberg discord server](https://discord.gg/D5ZR83W5KM)"}
{"instruction": "PyPulsar v0.1.3 released – React + Vite template, improved CLI, dynamic plugins & architecture clean", "input": "", "output": "PyPulsar v0.1.3 released – React + Vite template, improved CLI, dynamic plugins & architecture clean\nHi r/python!\n\nI just released **v0.1.3** of **PyPulsar** – a lightweight, fast framework for building native-feeling desktop apps (and eventually mobile) using pure Python on the backend + HTML/CSS/JS on the frontend. No Electron bloat, no need to learn Rust (unlike Tauri).\n\n[https://imgur.com/a/Mpx227t](https://imgur.com/a/Mpx227t)\n\nRepo: [https://github.com/dannyx-hub/PyPulsar](https://github.com/dannyx-hub/PyPulsar)\n\nKey highlights in v0.1.3:\n\n* **Official React + Vite template** Run pypulsar create my-app --template react-vite and get a modern frontend setup with hot-reloading, fast builds, and all the Vite goodies right out of the box.\n* **Big CLI improvements** Better template handling (especially React), smoother plugin installation, virtual environment creation during project setup, and new plugin management commands (list, install, etc.).\n* **Architecture refactor & cleanups** Refactored the core engine (BaseEngine → DesktopEngine separation), introduced a proper WindowManager + Api class for cleaner window & event handling, cleaned up pyproject.toml, added PyGObject for better Linux support, improved synchronous message handling, and more code organization. (This refactor also lays groundwork for future extensions like mobile support – Android work is ongoing but not production-ready yet; focus remains on solid desktop experience.)\n* **Other fixes & polish** Better plugin install logic, fixed print statements in engine, dependency updates, .gitignore tweaks, and general stability improvements.\n\nThe project is still in **early beta (0.1.x)**, so expect occasional breaking changes, but you get:\n\n* Tiny bundles (\\~5–15 MB)\n* Low memory usage (<100 MB, often 50–80 MB)\n* Native webviews (Edge on Windows, WebKit on macOS, GTK on Linux)\n* Full Python power in the backend (numpy, pandas, ML libs, whatever you need)\n* Secure Python ↔ JS communication via ACL (default-deny + event whitelisting)\n\nWorks great on Windows, macOS, and Linux right now.\n\nI’d love to hear your thoughts!\nAre you using something similar (pywebview + custom setup, eel, NiceGUI, Flet, Tauri with Python bindings…)? What features would you most want in a tool like this? Bug reports, feature ideas, or even early plugins are super welcome – the plan is to grow a nice CLI-driven plugin ecosystem.\n\nThanks for checking it out! 🚀\n[https://github.com/dannyx-hub/PyPulsar](https://github.com/dannyx-hub/PyPulsar)"}
{"instruction": "Lightweight Python helpers for Event Driven Programming", "input": "", "output": "Lightweight Python helpers for Event Driven Programming\nI 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.\n\n\nI 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.\n\nHas anyone used anything like this? I found PyEventus which seems to aim at this."}
{"instruction": "Two SBOMs for the same service never match and the SBOM tools I tried only cover one layer", "input": "", "output": "Two SBOMs for the same service never match and the SBOM tools I tried only cover one layer\nOur services are Python in containers and we generate one SBOM from the image and another from the lockfile. The two never agree and the gap is usually system packages the base image drags in. Customers now want one document per release and I end up stitching them together by hand. Im after something that covers the interpreter and the wheels and the system layer in a single pass. What are you running for this?"}
{"instruction": "Project showcase - skrub, machine learning with dataframes", "input": "", "output": "Project showcase - skrub, machine learning with dataframes\nHey everyone, I’m one of the developers of [skrub](https://skrub-data.org/stable/), an open-source package ([GitHub repo](https://github.com/skrub-data/skrub)) designed to simplify machine learning with dataframes.\n\n### **What my project does**\n\nSkrub bridges the gap between pandas/polars and scikit-learn by providing a collection of transformers for exploratory data analysis, data cleaning, feature engineering, and ensuring reproducibility across environments and between development and production.\n\n### Main features\n\n- **TableReport**: An interactive HTML tool that summarizes dataframes, offering insights into column distributions, data types, correlated columns, and more.\n\n- **Transformers** for feature engineering datetime and categorical data.\n\n- **TableVectorizer**: A scikit-learn-compatible transformer that encodes all columns in a dataframe and returns a feature matrix ready for machine learning models.\n\n- **tabular_pipeline**: A simple function to generate a machine learning pipeline for tabular data, tailored for either classification or regression tasks.\n\nSkrub also includes **Data Ops**, a framework that extends scikit-learn Pipelines to handle multi-table and complex input scenarios:\n\n- **DataOps Computational Graph**: Record all operations, their order, and parameters, and guarantee reproducibility.\n\n- **Replayability**: Operations can be replayed identically on new data.\n\n- **Automated Splitting**: By defining `X` and `y`, skrub handles sample splitting during validation, minimizing data leakage risks.\n\n- **Hyperparameter Tuning**: Any operation in the graph can be tuned and used in grid or randomized searches. You can optimize a model's learning rate, or evaluate whether a specific dataframe operation (joins/selections/filters...) is useful or not. Hyperparameter tuning supports scikit-learn and Optuna as backends.\n\n- **Result Exploration**: After hyperparameter tuning, explore results with a built-in parallel coordinate plot.\n\n- **Portability**: Save the computational graph as a single object (a \"learner\") for sharing or executing elsewhere on new data.\n\n### Target audience\n\nSkrub is intended to be used by data scientists that need to build pipelines for machine learning tasks.\n\nThe package is well tested and robust, and the hope is for people to put it into production.\n\n### Comparison\n\nSkrub slots in between data preparation (using pandas/polars) and scikit-learn’s machine learning models. It doesn’t replace either but leverages their strengths to function.\n\nI’m not aware of other packages that offer the exact same functionality as Skrub. If you know of any, I’d love to hear about them!\n\n### **Resources**\n\n- [Website](https://skrub-data.org/stable/)\n\n- [Example Gallery](https://skrub-data.org/stable/auto_examples/index.html)\n\n- [GitHub Repo](https://github.com/skrub-data/skrub)\n\nIf you'd rather watch a video about the library, we got you covered!\nWe presented skrub at Euroscipy 2025 [tutorial](https://www.youtube.com/watch?v=hbmfiBX5zZc) and Pydata Paris 2025 [talk](https://www.youtube.com/watch?v=k9MNMDpgdAk)"}
{"instruction": "NiceGooey: Generate (no AI :)) web UIs from your command line tool", "input": "", "output": "NiceGooey: Generate (no AI :)) web UIs from your command line tool\nSome while back, I created command line tools for a gaming community, with a wide audience of users. I found that, while the tools were found to be useful, the fact that they were purely CLI made them \"too technical\" for many people to use.\n\nThat's why I wrote **NiceGooey**, a library to easily generate a GUI from a command line tool implemented with the standard library's argparse module.\n\nThe idea is that, for the simplest use case, you only need to add a single line of code to an existing project. When running your program after that, a local web server is started and opens a browser page accessing your UI.\n\nScreenshots are available in the README file in the links below:\n\n[https://codeberg.org/atollk/NiceGooey/](https://codeberg.org/atollk/NiceGooey/)\n\n[https://github.com/atollk/NiceGooey](https://github.com/atollk/NiceGooey)\n\n[https://pypi.org/project/nicegooey/](https://pypi.org/project/nicegooey/)\n\nSince I know that AI-generated code and \"slop\" are a hot topic in online software communities, I added a section specific to AI usage in the project to the README. In short, there is no AI involved in the runtime, and none of the actual implementation was touched by coding agents, except for some easy-to-automate changes I required for refactorings along the way. I spent a few months to write this project by hand.\n\nI would be happy if this project can be of use to some of you. Do let me know if you build something with it :)\n\n**What My Project Does:** Creates a website to control your command line tool via UI instead of command line flags.\n\n**Target Audience:** Developers of tools who want to broaden their audience to less tech-savy users\n\n**Comparison:** The idea is based on [github.com/chriskiehl/Gooey](http://github.com/chriskiehl/Gooey) . While Gooey is a more mature solution, it sees no more active development and in my experience brings the issues and possibly aged feel that many people associate with native GUI programs.\n\nShoutout to the nicegui library (and team) which is the main dependency to render the Vue-based frontend from Python, and who quickly fixed a few bugs I encountered while developing NiceGooey."}
{"instruction": "Free ML Engineering roadmap for beginners", "input": "", "output": "Free ML Engineering roadmap for beginners\nI created a simple roadmap for anyone who wants to become a Machine Learning Engineer but feels confused about where to start.\n\nThe roadmap focuses on building strong fundamentals first and then moving toward real ML engineering skills.\n\nMain stages in the roadmap:\n\n• Python fundamentals\n• Math for machine learning (linear algebra, probability, statistics)\n• Data analysis with NumPy and Pandas\n• Machine learning with scikit-learn\n• Deep learning basics (PyTorch / TensorFlow)\n• ML engineering tools (Git, Docker, APIs)\n• Introduction to MLOps\n• Real-world projects and deployment\n\nThe idea is to move from learning concepts → building projects → deploying models.\n\nI’m still refining the roadmap and would love feedback from the community.\n\nWhat would you add or change in this path to becoming an ML Engineer?"}
{"instruction": "Why auto-fixing secrets in CI doesn’t really work", "input": "", "output": "Why auto-fixing secrets in CI doesn’t really work\nI have been messing around with automatically fixing hardcoded secrets in Python projects. the idea sounded simple,\ndetect secrets in CI - rewrite them to env vars - done.\n\nTechnically it works. you can do safe rewrites with AST and keep it deterministic. but people really don’t like CI modifying their code.\n\nEven when the change is safe, it still feels off. the main things I kept hearing,\n\n\\- CI should be read-only\n\\- people want to see changes before they happen\n\\- auto-fix in CI feels like losing control\n\nAfter a while I kind of agreed with that. what seems to work better is splitting it,\n\n\\- CI --> detection only (fail the build)\n\\- fixing --> done locally (pre-commit or manually)\n\nSo CI enforces the rule, but you’re not letting it touch your code.\nhow are you all handling this?\ndo you let CI fix stuff, or keep it strictly read-only?"}
{"instruction": "Project recognition in the era of AI slop", "input": "", "output": "Project recognition in the era of AI slop\nFirst off, I just want to say that this is not AI generated and I am genuinely asking a question on how to properly share a project that you're actually excited on and that actually has real world usage without being tossed into a void or told this is just AI slop.\n\nHow do you gain project recognition or share anymore? I wanted to share one of my projects that I've been working on for months as an example.\n\nI came to the subreddit thinking I would be able to just simply share my project and I got a warning saying that showcasing is no longer allowed because of the problem with tooling being just generated en masse at an infathomable speed. People were complaining so much, rightly so, that the subreddit laid down new rules and so did other subreddits.\n\nI followed the rules on each subreddit and posted into basically a void for projects thinking that people would want detailed and professional sounding wording and instead I was met with \"another AI slop tool\"  from multiple people. People left comments saying I was using buzzwords, except those words are used to describe the actual technical definition, such as \"bounded concurrency\".\n\nI thought that I should pay attention to my grammar and make sure it sounds decent, instead I was DM'd that I should just quit making AI generated content.\n\nMy project is literally used in two companies right now to help speed up AWS governance and security. I use my own project for my own AWS organization and accounts that I own. I figured people would like to have an easier \"control plane\" via python for AWS but that wasn't well received."}
{"instruction": "Its been 3 years now... your thoughts about trusted publisher on pypi", "input": "", "output": "Its been 3 years now... your thoughts about trusted publisher on pypi\nHow do you like using the trusted publisher feature to publish your packages, compared to the traditional methods.\n\nI wonder what is the adoption rate in the community.\n\nAlso, from security standpoint, how common is to have a human authorization step, using 2FA step to approve deployment?"}
{"instruction": "Astral's ty readiness for CI", "input": "", "output": "Astral's ty readiness for CI\nIf you were setting up your project/department/company CI pipelines today, would you feel comfortable using ty as the type checker, or would you stick with basedpyright/other alternative?\n\n&#x200B;\n\nI am currently setting up my own CI and am leaning towards basedpyright, as I've been using for some time, but ty seems to be developing nicely, although (as far as I know) it is not fully on-par with pyright."}
{"instruction": "Using pre-commit as a polyglot task runner: elegant or kludgy?", "input": "", "output": "Using pre-commit as a polyglot task runner: elegant or kludgy?\nPackage maintainers: does your `Makefile` or `justfile` delegate tool calls to [pre-commit](https://pre-commit.com/) (e.g., for your `lint all` targets)?\n\nI see a lot of modern repos doing it this way now. On one hand, I can see the elegance of it—`pre-commit` has basically evolved into an execution engine that manages isolated polyglot tool environments.\n\nBut it still just feels weird to me, almost like a layer violation. Maybe it's just because my mental model still views `pre-commit` strictly as a git-hook manager rather than what it has actually become.\n\nOne huge benefit, I guess, of having linting and quality tools delegated this way is parity: your CI pipeline, your pre-commit hooks, and your manual `justfile` targets all run the *exact* same tools in the *exact* same way.\n\nIt also solves the polyglot problem. Modern dev dependencies can't all be managed by one tool (like `uv`, `pip`, or `pnpm`) because some are Node, some are Python, some are Go, etc.\n\nCurious to hear how others are approaching this. Any strong reasons for / against delegating to `pre-commit` for your task runners vs. keeping them strictly decoupled?"}
{"instruction": "safezip - A small, zero-dependency wrapper for secure ZIP extraction", "input": "", "output": "safezip - A small, zero-dependency wrapper for secure ZIP extraction\nI wrote a small, zero-dependency wrapper for secure ZIP extraction.\n\n[https://github.com/barseghyanartur/safezip](https://github.com/barseghyanartur/safezip)\n\n**What My Project Does**\n\n`safezip` is a zero-dependency wrapper around Python's `zipfile` module that makes secure ZIP extraction the default. It protects against:\n\n* **ZipSlip protection**: Blocks relative paths, absolute paths, Windows UNC paths, Unicode lookalike attacks, and null bytes in filenames.\n* **ZIP bomb prevention**: Enforces per-member and cumulative decompression ratio limits at stream time — not based on untrusted header values.\n* **ZIP64 consistency checks**: Crafted archives with inconsistent ZIP64 extra fields are rejected before decompression begins.\n* **Symlink policy** — configurable: `REJECT` (default), `IGNORE`, or `RESOLVE_INTERNAL` (full chain verification).\n* **Atomic writes**: Extracts to a temp file first and only moves it to the destination if all checks pass. If something fails, you don't end up with half-extracted junk on your disk.\n* **Environment variable overrides**: All numeric limits can be set via `SAFEZIP_*` environment variables for containerised deployments.\n\n\nIt's meant to be an almost drop-in replacement. You can just do:\n\n    from safezip import safe_extract\n\n    safe_extract(\"path/to/file.zip\", \"/var/files/extracted/\")\n\n\nIf you need more control, there’s a `SafeZipFile` context manager that lets you tweak limits or monitor security events.\n\n    from safezip import SafeZipFile\n\n    with SafeZipFile(\"path/to/file.zip\") as zf:\n        print(zf.namelist())\n        zf.extractall(\"/var/files/extracted/\")\n\n\n**Target Audience**\n\nIf you're handling user uploads or processing ZIP files from untrusted sources, this might save you some headache. It's production-oriented but currently in beta, so feedback and edge cases are very welcome.\n\n**Comparison**\n\nThe standard library's `zipfile` module historically wasn't safe to use on untrusted files. Even the official docs warn against `extractall()` because of ZipSlip risks, and it doesn't do much to stop ZIP bombs from eating up your disk or memory. Python 3.12 did address some of this — `extractall()` now strips path components that would escape the target directory — but it still leaves meaningful gaps: no ZIP bomb protection, no stream-time size enforcement, no symlink policy, no ZIP64 consistency checks, and no atomic writes. `safezip` fills all of those. I got tired of writing the same boilerplate every time, so I packaged it up.\n\n\\----\n\nDocumentation: [https://safezip.readthedocs.io/en/latest/](https://safezip.readthedocs.io/en/latest/)"}
{"instruction": "pypimap.com: an interactive visualization map of pypi packages", "input": "", "output": "pypimap.com: an interactive visualization map of pypi packages\n[Data scientist Nael](https://www.reddit.com/user/naelaqel/) launched a website that visualizes pypi packages.\n\n[https://pypimap.com/](https://pypimap.com/)\n\nIt uses public dataset that can be found on [his kaggle](https://www.kaggle.com/datasets/naelaqel/pypi-daily-metadata-and-analytics-base-dataset/data)\n\nthe website is also opensource."}
{"instruction": "Recommendations and discussion on codebase visualizer and dependence mapper.", "input": "", "output": "Recommendations and discussion on codebase visualizer and dependence mapper.\nI've been looking at a few options like gitkrakens codemap. But I just haven't made a decision yet.\n\nThe biggest problem right now with AI assist is that so much gets spun up and it takes quite a while to ground myself in what has been written and how it all connects. I thought a viz tool would help tighten what I need to learn.\n\nHow do you handle this? Do you use these tools for this purpose? What have you liked and disliked about the tool you used?"}
{"instruction": "I built a small compiler that converts a GDScript-like language into Python (GDLite)", "input": "", "output": "I built a small compiler that converts a GDScript-like language into Python (GDLite)\nHi r/Python,\n\nI’ve been learning about language design and CLI tools, and I built a small project called GDLite.\n\n## What my project does\nGDLite is a lightweight scripting language that compiles into Python.\nYou write code in a simpler GDScript-like syntax and it generates a Python file that you can run normally.\n\nIt also supports importing Python modules and even importing external modules directly from GitHub.\n\nExample:\n\nhello.gdl\nfunc main():\n    print(\"Hello from GDL!\")\nmain()\n\nCompile:\ngdlc hello.gdl\n\nRun:\npython hello.py\n\n## Target audience\nThis project is mainly for:\n• People learning compilers or language design\n• Python users who want a simpler scripting syntax\n• Termux/Linux users who like CLI tools and experimentation\n\nThis is NOT meant for production yet — it’s an experimental learning project.\n\n## Why I made this / comparison\nI was inspired by GDScript from Godot.\nI like its simple syntax, but I wanted something that compiles into Python and can use Python libraries.\n\nSo GDLite acts as a lightweight scripting layer on top of Python.\n\n## Source code\nhttps://github.com/Lintang143/GDLC-GDLite-Compiler-\n\nI would really appreciate feedback, ideas, or criticism 🙂"}
{"instruction": "I ended building an oversimplfied durable workflow engine after overcomplicating my data pipelines", "input": "", "output": "I ended building an oversimplfied durable workflow engine after overcomplicating my data pipelines\nI've been running data ingestion pipelines in Python for a few years. pull from APIs, validate, transform, load into Postgres. The kind of stuff that needs to survive crashes and retry cleanly, but isn't complex enough to justify a whole platform.\n\nI tried the established tools and they're genuinely powerful. Temporal has an incredible ecosystem and is battle-tested at massive scale.\n\nPrefect and Airflow are great for scheduled DAG-based workloads. But every time I reached for one, I kept hitting the same friction: I just wanted to write normal Python functions and make them durable. Instead I was learning new execution models, seprating \"activities\" from \"workflow code\", deploying sidecar services, or writing YAML configs. For my usecase, it was like bringing a forklift to move a chair.\n\nSo I ended up building Sayiir.\n\n# What this project Does\n\nSayiir is a durable workflow engine with a Rust core and native Python bindings (via PyO3). You define tasks as plain Python functions with a `@task` decorator, chain them with a fluent builder, and get automatic checkpointing and crash recovery without any DSL, YAML, or seperate server to deploy.\n\nPython is a first-class citizen: the API uses native decorators, type hints, and async/await. It's not a wrapper around a REST API, it's direct bindings into the Rust engine running in your process.\n\nHere's what a workflow looks like:\n\n    from sayiir import task, Flow, run_workflow\n\n    @task\n    def fetch_user(user_id: int) -> dict:\n        return {\"id\": user_id, \"name\": \"Alice\"}\n\n    @task\n    def send_email(user: dict) -> str:\n        return f\"Sent welcome to {user['name']}\"\n\n    workflow = Flow(\"welcome\").then(fetch_user).then(send_email).build()\n    result = run_workflow(workflow, 42)\n\nThats it. No registration step, no activity classes, no config files. When you need durability, swap in a backend:\n\n    from sayiir import run_durable_workflow, PostgresBackend\n\n    backend = PostgresBackend(\"postgresql://localhost/sayiir\")\n    status = run_durable_workflow(workflow, \"welcome-42\", 42, backend=backend)\n\nIt also supports retries, timeouts, parallel execution (fork/join), conditional branching, loops, signals/external events, pause/cancel/resume, and OpenTelemetry tracing. Persistence backends: in-memory for dev, PostgreSQL for production.\n\n# Target Audience\n\nDevelopers who need durable workflows but find the existing platforms overkill for their usecase. Think data pipelines, multi-step API orchestration, onboarding flows, anything where you want crash recovery and retries but don't want to deploy and manage a separate workflow server. Not a toy project, but still young.\n\nit's usable in production and my empoler considers using it for internal clis, and ETL processes.\n\n# Comparison\n\n* **Temporal**: Much more mature and feature-complete, huge community, but requires a separate server cluster and imposes determinism constraints on workflow code and steep learning curve for the api. Sayiir runs embedded in your process with no coding restrictions.\n* **Prefect / Airflow**: Great for scheduled DAG workloads and data orchestration at scale. Sayiir is more lightweight — no scheduler, no UI, just a library you import. Better suited for event-driven pipelines than scheduled batch jobs.\n* **Celery / BullMQ-style queues**: These are task queues, not workflow engines. You end up hand-rolling checkp"}
{"instruction": "Schema diagrams in GitHub PRs: what actually works on your team?", "input": "", "output": "Schema diagrams in GitHub PRs: what actually works on your team?\nWorking on a Django project with a fairly large data model, and I keep hitting the same friction: when a PR changes models or relationships, there's no good way to show the reviewer what changed at the schema level. The migration file and ORM show it, sure — but I'm a visual person, and for non-trivial changes a drawing really helps reviewers grasp what's going on.\n\nThe problem is friction. Nobody wants to redraw a diagram for every PR, so nobody does. And with AI accelerating how fast schemas change, the gap between \"what the code says\" and \"what the team last visualized\" is getting wider.\n\nThings we've tried and mostly abandoned:\n\n* Mermaid diagrams in markdown\n* ASCII tables\n* PNG exports from dbdiagram / drawio\n* Whiteboard photos\n* Nothing (the honest winner)\n\nWhat's the highest-friction part for you — creating the diagram, keeping it updated, or getting teammates to actually look at it? Curious especially about Django shops but interested in any stack."}
{"instruction": "FastAPI Conf 2026 - first ever official FastAPI conference", "input": "", "output": "FastAPI Conf 2026 - first ever official FastAPI conference\nHello folks!\n\nWe're organizing the first ever official FastAPI Conf, in Amsterdam, October 28th, 2026. ✨\n\nIt's gonna be very cool, great speakers, and announcements too.\n\nEarly Bird tickets are now available (until August 23th).\n\nHere's the website with info, tickets, and newsletter: [https://fastapiconf.com](https://fastapiconf.com)"}
{"instruction": "Spectra: Python pipeline to turn bank CSV/PDF exports into an automated finance dashboard", "input": "", "output": "Spectra: Python pipeline to turn bank CSV/PDF exports into an automated finance dashboard\n**What my project does**\nSpectra ingests bank CSV/PDF exports, normalizes transactions, categorizes them with an LLM, detects recurring payments (subscriptions/salary), converts currencies using historical FX rates, and updates a multi-tab Google Sheets dashboard. It’s idempotent (SQLite + hashes), so reruns don’t create duplicates.\n\n**Target audience**\nPeople who want personal finance tracking without Open Banking integrations and without locking data into closed fintech platforms, and who prefer a file-based workflow they fully control (especially EU/Italian bank exports). Built as a personal tool, but usable by others.\n\n**Comparison**\nCompared to typical budgeting apps, Spectra doesn’t require direct bank access and keeps everything transparent in Google Sheets. Compared to regex/rules-only scripts, it adds LLM-based categorization with a feedback loop (overrides) plus automation via GitHub Actions.\n\nRepo: [https://github.com/francescogabrieli/Spectra]()\nFeedback on architecture / edge cases is welcome."}
{"instruction": "What would you want in a modern Python testing framework?", "input": "", "output": "What would you want in a modern Python testing framework?\nTools like uv and ruff have shown us what is possible when we take the time to rethink Python tooling, as well as implement parts in Rust for speed improvements. What would you, the community, want to see in a modern Python testing framework that could be a successor to the tried and true pytest?\n\nSome off the cuff ideas I think of:\n* Fast test discovery via Rust\n* Explicit fixture import (no auto discoverable conftest.py magic)\n* Monorepo / workspace support\n* Built-in parallel test execution\n* Built-in asyncio support"}
{"instruction": "pfst 0.3.0: High-level Python source manipulation", "input": "", "output": "pfst 0.3.0: High-level Python source manipulation\nI’ve been developing pfst (Python Formatted Syntax Tree) and I’ve just released version 0.3.0. The major addition is structural pattern matching and substitution. To be clear, this is not regex string matching but full structural tree matching and substitution.\n\n**What it does**:\n\nAllows high level editing of Python source and AST tree while handling all the weird syntax nuances without breaking comments or original layout. It provides a high-level Pythonic interface and handles the 'formatting math' automatically.\n\n**Target Audience**:\n\n* Working with Python source, refactoring, instrumenting, renaming, etc...\n\n**Comparison**:\n\n* vs. LibCST: pfst works at a higher level, you tell it what you want and it deals with all the commas and spacing and other details automatically.\n* vs. Python ast module: pfst works with standard AST nodes but unlike the built-in ast module, pfst is format-preserving, meaning it won't strip away your comments or change your styling.\n\n**Links**:\n\n* GitHub: [https://github.com/tom-pytel/pfst](https://github.com/tom-pytel/pfst)\n* PyPI: [https://pypi.org/project/pfst/](https://pypi.org/project/pfst/)\n* Documentation: [https://tom-pytel.github.io/pfst/](https://tom-pytel.github.io/pfst/)\n\nI would love some feedback on the API ergonomics, especially from anyone who has dealt with Python source transformation and its pain points.\n\n**Example**:\n\nReplace all `Load`\\-type expressions with a `log()` passthrough function.\n\n    from fst import *  # pip install pfst, import fst\n    from fst.match import *\n\n    src = \"\"\"\n    i = j.k = a + b[c]  # comment\n\n    l[0] = call(\n        i,  # comment 2\n        kw=j,  # comment 3\n    )\n    \"\"\"\n\n    out = FST(src).sub(Mexpr(ctx=Load), \"log(__FST_)\", nested=True).src\n\n    print(out)\n\nOutput:\n\n    i = log(j).k = log(a) + log(log(b)[log(c)])  # comment\n\n    log(l)[0] = log(call)(\n        log(i),  # comment 2\n        kw=log(j),  # comment 3\n    )\n\nMore substitution examples: [https://tom-pytel.github.io/pfst/fst/docs/d14\\_examples.html#structural-pattern-substitution](https://tom-pytel.github.io/pfst/fst/docs/d14_examples.html#structural-pattern-substitution)"}
{"instruction": "Thursday Daily Thread: Python Careers, Courses, and Furthering Education!", "input": "", "output": "Thursday Daily Thread: Python Careers, Courses, and Furthering Education!\n# Weekly Thread: Professional Use, Jobs, and Education 🏢\n\nWelcome 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**.\n\n---\n\n## How it Works:\n\n1. **Career Talk**: Discuss using Python in your job, or the job market for Python roles.\n2. **Education Q&A**: Ask or answer questions about Python courses, certifications, and educational resources.\n3. **Workplace Chat**: Share your experiences, challenges, or success stories about using Python professionally.\n\n---\n\n## Guidelines:\n\n- This thread is **not for recruitment**. For job postings, please see r/PythonJobs or the recruitment thread in the sidebar.\n- Keep discussions relevant to Python in the professional and educational context.\n\n---\n\n## Example Topics:\n\n1. **Career Paths**: What kinds of roles are out there for Python developers?\n2. **Certifications**: Are Python certifications worth it?\n3. **Course Recommendations**: Any good advanced Python courses to recommend?\n4. **Workplace Tools**: What Python libraries are indispensable in your professional work?\n5. **Interview Tips**: What types of Python questions are commonly asked in interviews?\n\n---\n\nLet's help each other grow in our careers and education. Happy discussing! 🌟"}
{"instruction": "Follow up: Clientele - an API integration framework for Python", "input": "", "output": "Follow up: Clientele - an API integration framework for Python\nHello pythonistas, two weeks ago I shared a [blog post](https://www.reddit.com/r/Python/comments/1q1udpj/blog_post_a_different_way_to_think_about_python/) about an alternative way of building API integrations, heavily inspired by the developer experience of python API  frameworks.\n\n**What My Project Does**\n\nClientele lets you focus on the behaviour you want from an API, and let it handle the rest - networking, hydration, caching, and data validation. It uses strong types and decorators to build a reliable and loveable API integration experience.\n\nI have been working on the project day and night - testing, honing, extending, and even getting contributions from other helpful developers. I now have the project in a stable state where I need more feedback on real-life usage and testing.\n\nHere are some examples of it in action:\n\n## Simple API\n\n```python\nfrom clientele import api\n\nclient = api.APIClient(base_url=\"https://pokeapi.co/api/v2\")\n\n@client.get(\"/pokemon/{pokemon_name}\")\ndef get_pokemon_info(pokemon_name: str, result: dict) -> dict:\n    return result\n```\n\n## Simple POST request\n\n```python\nfrom clientele import api\n\nclient = api.APIClient(base_url=\"https://httpbin.org\")\n\n@client.post(\"/post\")\ndef post_input_data(data: dict, result: dict) -> dict:\n    return result\n```\n\n## Streaming responses\n\n```python\nfrom typing import AsyncIterator\nfrom pydantic import BaseModel\nfrom clientele import api\n\nclient = api.APIClient(base_url=\"http://localhost:8000\")\n\nclass Event(BaseModel):\n    text: str\n\n@client.get(\"/events\", streaming_response=True)\nasync def stream_events(*, result: AsyncIterator[Event]) -> AsyncIterator[Event]:\n    return result\n```\n\nNew features include:\n\n- Handle streaming responses for Server Sent Events\n- Handle custom response parsing with callbacks\n- Sensible HTTP caching decorator with extendable backends\n- A Mypy plugin to handle the way the library injects parameters\n- Many many tweaks and updates to handle edge-case OpenAPI schemas\n\nPlease star ⭐ the project, give it a download and let me know what you think: https://github.com/phalt/clientele"}
{"instruction": "I’ve published a new audio DSP/Synthesis package to PyPI", "input": "", "output": "I’ve published a new audio DSP/Synthesis package to PyPI\n\\*\\*What My Project Does\\*\\* - It’s called audio-dsp. It is a comprehensive collection of DSP tools including Synthesizers, Effects, Sequencers, MIDI tools, and Utilities.\n\n\\*\\*Target Audience\\*\\* - I am a music producer (25 years) and programmer (15 years), so I built this with a focus on high-quality rendering and creative design. If you are a creative coder or audio dev looking to generate sound rather than just analyze it, this is for you.\n\n\\*\\*Comparison\\*\\* - Most Python audio libraries focus on analysis (like librosa) or pure math (scipy). My library is different because it focuses on musicality and synthesis. It provides the building blocks for creating music and complex sound textures programmatically.\n\nTry it out:\n\npip install audio-dsp\n\nGitHub: [https://github.com/Metallicode/python\\_audio\\_dsp](https://github.com/Metallicode/python_audio_dsp)\n\nI’d love to hear your feedback!"}
{"instruction": "OAuth 2.0 in CLI Apps written in Python", "input": "", "output": "OAuth 2.0 in CLI Apps written in Python\n[https://jakabszilard.work/posts/oauth-in-python](https://jakabszilard.work/posts/oauth-in-python)\n\nI was creating a CLI app in Python that needed to communicate with an endpoint that needed OAuth 2.0, and I've realized it's not as trivial as I thought, and there are some additional challenges compared to a web app in the browser in terms of security and implementation. After some research I've managed to come up with an implementation, and I've decided to collect my findings in a way that might end up being interesting / useful for others."}
{"instruction": "MolBuilder: pure-Python molecular engineering -- from SMILES to manufacturing plans", "input": "", "output": "MolBuilder: pure-Python molecular engineering -- from SMILES to manufacturing plans\n**What My Project Does:**\n\nMolBuilder is a pure-Python package that handles the full chemistry pipeline from molecular structure to production planning. You give it a molecule as a SMILES string and it can:\n\n1. Parse SMILES with chirality and stereochemistry\n2. Plan synthesis routes (91 hand-curated reaction templates, beam-search retrosynthesis)\n3. Predict optimal reaction conditions (analyzes substrate sterics and electronics to auto-select templates)\n4. Select a reactor type (batch, CSTR, PFR, microreactor)\n5. Run GHS safety assessment (69 hazard codes, PPE requirements, emergency procedures)\n6. Estimate manufacturing costs (materials, labor, equipment, energy, waste disposal)\n7. Analyze scale-up (batch sizing, capital costs, annual capacity)\n\nThe core is built on a graph-based molecule representation with adjacency lists. Functional group detection uses subgraph pattern matching on this graph (24 detectors). The retrosynthesis engine applies reaction templates in reverse using beam search, terminating when it hits purchasable starting materials (\\~200 in the database). The condition prediction layer classifies substrate steric environment and electronic character, then scores and ranks compatible templates.\n\nPython-specific implementation details:\n\n* Dataclasses throughout for the reaction template schema, molecular graph, and result types\n* NumPy/SciPy for 3D coordinate generation (distance geometry + force field minimization)\n* Molecular dynamics engine with Velocity Verlet integrator\n* File I/O parsers for MOL/SDF V2000, PDB, XYZ, and JSON formats\n* Also ships as a FastAPI REST API with JWT auth, RBAC, and Stripe billing\n\nInstall and example:\n\n`pip install molbuilder`\n\n`from molbuilder.process.condition_prediction import predict_conditions`\n\n`result = predict_conditions(\"CCO\", reaction_name=\"oxidation\", scale_kg=10.0)`\n\n`print(result.best_match.template_name)             # TEMPO-mediated oxidation`\n\n`print(result.best_match.conditions.temperature_C)   # 5.0`\n\n`print(result.best_match.conditions.solvent)          # DCM/water (biphasic)`\n\n`print(result.overall_confidence)                     # high`\n\n\n1,280+ tests (pytest), Python 3.11+, CI on 3.11/3.12/3.13. Only dependencies are numpy, scipy, and matplotlib.\n\nGitHub: [https://github.com/Taylor-C-Powell/Molecule\\_Builder](https://github.com/Taylor-C-Powell/Molecule_Builder)\n\nTutorials: [https://github.com/Taylor-C-Powell/Molecule\\_Builder/tree/main/tutorials](https://github.com/Taylor-C-Powell/Molecule_Builder/tree/main/tutorials)\n\n**Target Audience:**\n\nProduction use. Aimed at computational chemists, process chemists, and cheminformatics developers who need programmatic access to synthesis planning and process engineering. Also useful for teaching organic chemistry and chemical engineering - the tutorials are designed as walkable Jupyter notebooks. Currently used by the author in a production SaaS API.\n\n**Comparison:**\n\nvs. RDKit: RDKit is the standard open-source cheminformatics toolkit but requires conda or C++ compilation and focuses on molecular properties (fingerprints, substructure search, descriptors). MolBuilder is pip-installable (pure Python, no C extensions) and focuses on the process engineering side -- going from \"I have a molecule\" to \"here's how to manufacture it at scale.\" Not a replacement for RDKit's molecular modeling depth.\n\nvs. Reaxys/SciFinder: Commercial databases with mil"}
{"instruction": "Does anyone actually use Pypy or Graalpy (or any other runtimes) in a large scale/production area?", "input": "", "output": "Does anyone actually use Pypy or Graalpy (or any other runtimes) in a large scale/production area?\nTitle.\n\nQuite interested in these two, especially Graalpy's AOT capabilities, and maybe Pypy's as well. How does it all compare to Nuitka's AOT compiler, and CPython as a base benchmark?"}
{"instruction": "PDF Extractor (OCR/selectable text)", "input": "", "output": "PDF Extractor (OCR/selectable text)\nI have a project that I am working on but I am facing a couple issues.\n\nIn short, my project parses what is inside a pdf order and returns the result to user. The roadblocks Iam in currently is that it works OK for known/seen templates of pdf orders as well as unseen pdf orders. My biggest issue is if the pdf order is non-selectable text/scanned which means it requires OCR to extract the text. I have tried the OCRmyPDF+Tesseract but it misses lines and messes up with the quantity etc...\n\n\nWhat's there that can resolve OCR accurately?\n\nP.S. I also tried PaddleOCR but it never finishes the job and keeps the app on a loop with no result."}
{"instruction": "How and why to run modified Python code using the ast module", "input": "", "output": "How and why to run modified Python code using the ast module\nI've written a [blog post](https://pydantic.dev/articles/eval-type-backport) explaining how to use the `ast` module to parse Python code into a structure that you can understand precisely, manipulate to your will, and execute. This lets you achieve things that are otherwise difficult or impossible.\n\nI'm using the 'Discussion' flair instead of 'Tutorial' because I want people to read and share their opinions about the last part of the article where I explain why I think metaprogramming like this is a relevant skill, especially in the age of AI. Among other things, I claim that OpenAI acquiring Astral may be more about general purpose agents than coding agents.\n\nI'm planning to do a series of articles about Python metaprogramming, so keen to hear what people think of this post in general."}
{"instruction": "I built a Python DSL for creating C4 models and diagrams", "input": "", "output": "I built a Python DSL for creating C4 models and diagrams\nHello!\n\nLast year, I started writing a Python C4 model authoring tool, and it has come to a point where I feel good enough to share it with you guys so you can start playing around with it locally and render the C4 model views with PlantUML.\n\nGitHub repo: [https://github.com/amirulmenjeni/buildzr](https://github.com/amirulmenjeni/buildzr)\n\nDocumentation here: [https://buildzr.dev](https://buildzr.dev/)\n\n# What My Project Does\n\nbuildzr is a [Structurizr](https://structurizr.com/) authoring tool for Python programmers. It allows you to declaratively or procedurally author Structurizr models and diagrams.\n\nIf you're not familiar with Structurizr, it is both an open standard (see [Structurizr JSON schema](https://github.com/structurizr/json)) and a [set of tools](https://docs.structurizr.com/usage) for building software architecture diagrams as code. Structurizr derives its architecture modeling paradigm based on the [C4 model](https://c4model.com/), the modeling language for describing software architectures and their relationships.\n\nIn Structurizr, you define architecture models (System Context, Container, Component, and Code) and their relationships first. And then, you can re-use the models to present multiple perspectives, views, and stories about your architecture.\n\nbuildzr supercharges this workflow with Pythonic syntax sugar and intuitive APIs that make modeling as code more fun and productive.\n\n# Target Audience\n\nUse buildzr if you want to have an intuitive and powerful tool for writing C4 architecture models:\n\n* **Intuitive Pythonic Syntax**: Use Python's context managers (`with` statements) to create nested structures that naturally mirror your architecture's hierarchy. See the [example](https://github.com/amirulmenjeni/buildzr#quick-example).\n* **Programmatic Creation**: Use buildzr's DSL APIs to programmatically create C4 model architecture diagrams. Great for automation!\n* **Advanced Styling**: Style elements beyond just tags --- target by direct reference, type, group membership, or custom predicates for fine-grained visual control. Just take a look at [Styles](https://buildzr.dev/user-guide/styles/)!\n* **Cloud Provider Themes**: Add AWS, Azure, Google Cloud, Kubernetes, and Oracle Cloud icons to your diagrams with IDE-discoverable constants. No more memorizing tag strings! See [Themes](https://buildzr.dev/user-guide/themes/).\n* **Standards Compliant**: Stays true to the [Structurizr JSON schema](https://github.com/structurizr/json) standards. buildzr uses [datamodel-code-generator](https://github.com/koxudaxi/datamodel-code-generator) to automatically generate the low-level representation of the Workspace model.\n* **Rich Toolchain**: Uses the familiar Python programming language and its rich toolchains to write software architecture models and diagrams!\n\nQuick example, so you can get the idea (more examples and explanations at [https://buildzr.dev](https://buildzr.dev)):\n\n    from buildzr.dsl import (\n        Workspace,\n        SoftwareSystem,\n        Person,\n        Container,\n        SystemContextView,\n        ContainerView,\n        desc,\n        Group,\n        StyleElements,\n    )\n    from buildzr.themes import AWS\n\n    with Workspace('w') as w:\n\n        # Define your models (architecture elements and their relationships).\n\n        with Group(\"My Company\") as my_company:\n            u = Person('Web Application User')\n            webapp = SoftwareSystem('"}
{"instruction": "Does Python have a GIL per process?", "input": "", "output": "Does Python have a GIL per process?\nI am trying to learn some internals but this is not clear. Does every process have a single GIL? Or there is one per machine?\n\nIf that is there for GC, then the memory is unique per process, so should be one GIL per process. Also \\`multiprocessing\\` says that it creates real parallelism, so that should be the case.\n\n\nI am unable to find a confirmation in other places."}
{"instruction": "Introducing Scythe: An SQL Compiler and Linter in Rust, with Codegen support for 10 languages", "input": "", "output": "Introducing Scythe: An SQL Compiler and Linter in Rust, with Codegen support for 10 languages\nHi Peeps,\n\nI released [Scythe](https://github.com/Goldziher/scythe) — an SQL compiler that generates type-safe database access code from plain SQL. If you're familiar with [sqlc](https://github.com/sqlc-dev/sqlc), the concept is similar — sqlc was a direct inspiration. Since Scythe treats SQL as the source of truth, it also ships with robust SQL linting and formatting — 93 rules covering correctness, performance, style, and naming conventions, powered by a built-in [sqruff](https://github.com/quarylabs/sqruff) integration.\n\n## Why compile SQL?\n\nORMs add unnecessary bloat and complexity. SQL as the source of truth, from which you generate type-safe and precise code, gives you most of the benefits of ORMs without the cruft and hard-to-debug edge cases.\n\nThis is common practice in Go, where sqlc is widely used. I personally also use it in Rust — I used sqlc with the community-provided Rust plugin, which is solid. But sqlc has limitations: type inference for complex joins, nullability propagation, and multi-language support are areas where I wanted more.\n\n## What Scythe does differently\n\nScythe has a modular, trait-based architecture built in Rust. It uses engine-specific manifests and Jinja templates to make backends highly extensible. Out of the box it supports all major backend languages:\n\n- Rust (sqlx, tokio-postgres)\n- Python (psycopg3, asyncpg, aiomysql, aiosqlite)\n- TypeScript (postgres.js, pg, mysql2, better-sqlite3)\n- Go (pgx, database/sql)\n- Java (JDBC)\n- Kotlin (JDBC)\n- C# (Npgsql, MySqlConnector, Microsoft.Data.Sqlite)\n- Elixir (Postgrex, MyXQL, Exqlite)\n- Ruby (pg, mysql2, sqlite3)\n- PHP (PDO)\n\nIt also supports multiple databases — PostgreSQL, MySQL, and SQLite — with more planned.\n\nMost languages have several driver options per database. For example, in Rust you can target sqlx or tokio-postgres. In Python, you can choose between psycopg3 (sync), asyncpg (async PG), aiomysql (async MySQL), or aiosqlite (async SQLite). The engine-aware architecture means adding a new database for an existing driver is often just a manifest file.\n\nBeyond codegen, Scythe includes 93 SQL lint rules (22 custom + 71 via sqruff integration), SQL formatting, and a migration tool for sqlc users.\n\n- [GitHub](https://github.com/Goldziher/scythe)\n- [Documentation](https://goldziher.github.io/scythe)\n- [crates.io](https://crates.io/crates/scythe-cli)"}
{"instruction": "nitro-pandas v0.2.0 — drop-in pandas replacement backed by Polars (+ new profile_compare tool)", "input": "", "output": "nitro-pandas v0.2.0 — drop-in pandas replacement backed by Polars (+ new profile_compare tool)\nI’ve been frustrated for a while with how slow pandas gets on large CSVs. Polars is fast but the API is different enough that migrating existing pipelines is painful. So I built nitro-pandas: you replace import pandas as pd with import nitro\\_pandas as npd and that’s literally it. Same API, Polars under the hood.\n\nThe v0.2.0 release (shipped last month) adds the feature I’m actually most excited about: profile\\_compare. You wrap your existing pandas function, and it runs it line-by-line under both backends and shows you exactly where the speedup comes from:\n\n**Line**  **Source**                          **pandas**     **nitro**     **Gain**\n  5   df = pd. read\\_csv(\"data.csv\")    13.04s     1.09s     12.0x ↑\n\n  6   df = df.rename(columns={...})     0.11s     0.001s    80x  ↑\n\nBenchmarked on a real dataset (\\~3M rows, Amazon Books Reviews). Overall pipeline: 8.6x faster, mostly on I/O, groupby, and string ops — which is where pandas really drags in production.\n\nThe fallback mechanism also makes migration safe: if a method isn’t natively implemented yet, it falls back to pandas silently (with an optional warning), so nothing breaks.\n\nWould love feedback, especially on edge cases where the pandas compatibility layer misbehaves.\n\nGitHub: https://github.com/Wassim17Labdi/nitro-pandas\nPyPI: pip install nitro-pandas"}
{"instruction": "Anyone using Nix for production Python projects?", "input": "", "output": "Anyone using Nix for production Python projects?\nHi! I’m a huge fan of Nix and similar approaches to reproducible development environments, and I’m curious what people in the Python community think about it.\n\nHave any of you used Nix with Python projects for development environments, CI, deployment, or production?\n\nIf so, what has the experience been like? What worked well, and where did you run into friction?\n\nI’m especially curious about the learning curve. Do you think Nix itself is the main barrier, or is part of the problem that there isn’t as much Python-specific guidance, tooling, and documentation around using it?\n\nAnd for those who haven’t used it: would better Python-focused learning material and examples make you more likely to give it a try?"}
{"instruction": "TimeTracer v1.6 Update: Record & Replay debugging now supports Starlette + Dashboard Improvements", "input": "", "output": "TimeTracer v1.6 Update: Record & Replay debugging now supports Starlette + Dashboard Improvements\n**What My Project Does** TimeTracer records your backend API traffic (inputs, database queries, external HTTP calls) into JSON files called \"cassettes.\" You can then replay these cassettes locally to reproduce bugs instantly without needing the original database or external services to be online. It's essentially \"time travel debugging\" for Python backends, allowing you to capture a production error and step through it on your local machine.\n\n**Target Audience** Python backend developers (FastAPI, Django, Flask, Starlette) who want to debug complex production issues locally without setting up full staging environments, or who want to generate regression tests from real traffic.\n\n**Comparison** most tools either *monitor* traffic (OpenTelemetry, Datadog) or *mock* it for tests (VCR.py). TimeTracer captures production traffic and turns it into local, replayable test cases. Unlike VCR.py, it captures the *incoming* request context too, not just outgoing calls, making it a full-system replay tool.\n\n**What's New in v1.6**\n\n* **Starlette Support:** Full compatibility with Starlette applications (and by extension FastAPI).\n* **Deep Dependency Tracking:** The new dashboard visualizes the exact chain of dependency calls (e.g., your API -> GitHub API -> Database) for every request.\n* **New Tutorial:** I've written a guide on debugging 404 errors using this workflow (link in comments).\n\n**Source Code** [https://github.com/usv240/timetracer](https://github.com/usv240/timetracer)\n\n**Installation** \n\n    pip install timetracer"}
{"instruction": "Shellman — a TUI file manager I built in Python", "input": "", "output": "Shellman — a TUI file manager I built in Python\n**What My Project Does**\n\nShellman is a terminal file manager that lets you navigate, edit, copy, move, delete, and archive files entirely from the keyboard. It has a dual-panel layout with a directory tree on the left and file list on the right. Other features include a built-in text editor with syntax highlighting for 15+ languages, git status indicators next to files, bulk file selection, full undo support, real-time filtering, sort options, and archive creation and extraction — all without leaving the terminal.\n\n**Target Audience**\n\nDevelopers and power users who live in the terminal and want a capable file manager that doesn't require a GUI or a mouse. This is my first app and it's built for everyone (hopefully). Prebuilt binaries are available for Linux (deb and rpm), Windows, and macOS.\n\n**Comparison**\n\nThe closest alternatives are Midnight Commander (mc) and ranger. Midnight Commander is powerful but has a dated interface and steep learning curve. Ranger is excellent but requires configuration to get basic features working. Shellman aims to be immediately usable out of the box with sensible defaults, a modern look powered by Textual, and a few unique features.\n\nWould love some feedback on stuff to add and what to do next.\n\nGitHub: [https://github.com/Its-Atharva-Gupta/Shellman](https://github.com/Its-Atharva-Gupta/Shellman)"}
{"instruction": "Introducing dbslice - extract minimal, referentially-intact subsets from PostgreSQL", "input": "", "output": "Introducing dbslice - extract minimal, referentially-intact subsets from PostgreSQL\nCopying an entire production database to your machine is infeasible. But reproducing a bug often requires having the exact data that caused it. dbslice solves this by extracting only the records you need, following foreign key relationships to ensure referential integrity.\n\n## What My Project Does\n\ndbslice takes a single seed record (e.g., `orders.id=12345`) and performs a BFS traversal across all foreign key relationships, collecting only the rows that are actually connected. The output is topologically sorted SQL (or JSON/CSV) that you can load into a local database with zero FK violations. It also auto-anonymizes PII before data leaves production — emails, names, and phone numbers are replaced with deterministic fakes.\n\n```sh\nuv tool install dbslice\ndbslice extract postgres://prod/shop --seed \"orders.id=12345\" --anonymize\n```\n\nOne command. 47 rows from 6 tables instead of a 40 GB pg_dump.\n\n## Target Audience\n\nBackend developers and data engineers who work with PostgreSQL in production. Useful for local development, bug reproduction, writing integration tests against realistic data, and onboarding new team members without giving them access to real PII. Production-ready — handles cycles, self-referential FKs, and large schemas.\n\n## Comparison\n\n- **pg_dump**: Dumps the entire database or full tables. No way to get a subset of related rows. Output is huge and contains PII.\n- **pg_dump with --table**: Lets you pick tables but doesn't follow FK relationships — you get broken references.\n- **Manual SQL queries**: You can write them yourself, but getting the topological order right across 15+ tables with circular FKs is painful and error-prone.\n- **Jailer**: Java-based, requires a config file and GUI setup. dbslice is zero-config — it introspects the schema automatically.\n\nGitHub: https://github.com/nabroleonx/dbslice"}
{"instruction": "PyCon US 2026: Typing Summit", "input": "", "output": "PyCon US 2026: Typing Summit\nFor those who are going to PyCon US this year, consider attending the [Typing Summit](https://discuss.python.org/t/pycon-2026-typing-summit-thu-may-14-1-5pm/106354) on Thursday, May 14. As with last year, the summit is organized jointly by Carl (Astral, Ty maintainer) & Steven (Meta, Pyrefly maintainer).\n\nAnyone interested in typing in Python is welcome to attend: there will be interesting scheduled talks and opportunities to chat with type checker maintainers, type stub authors, and members of the typing council.\n\nNo prior experience is required - last year's summit had plenty of hobbyists and students in attendance. I personally learned a lot from the talks, despite not having a Master's degree :)\n\nIf you're planning to go, the [announcement thread](https://discuss.python.org/t/pycon-2026-typing-summit-thu-may-14-1-5pm/106354) has an interest form where you can tell the summit organizers what topics you're interested in hearing about, or propose a potential talk for the summit."}
{"instruction": "Blog: What's type-coverage, and why should I care?", "input": "", "output": "Blog: What's type-coverage, and why should I care?\nThis post is a quick primer on measuring type coverage and how it can be useful for library maintainers or those seeking to adopt types in their codebase.\n\nTL;DR:\n\n- Type coverage measures what percentage of your codebase's symbols are type-annotated.\n- Optionally, you can choose to only include publicly-exported symbols.\n- You can use it similarly to how you would use test coverage.\n\nThe blog post specifically focuses on Pyrefly's `coverage` command, which is being used to track type coverage for popular libraries such as numpy, scipy-stubs, polars, sh, and narwhals.\n\nRead the full blog here: https://pyrefly.org/blog/why-type-coverage/"}
{"instruction": "Friday Daily Thread: r/Python Meta and Free-Talk Fridays", "input": "", "output": "Friday Daily Thread: r/Python Meta and Free-Talk Fridays\n# Weekly Thread: Meta Discussions and Free Talk Friday 🎙️\n\nWelcome to Free Talk Friday on /r/Python! This is the place to discuss the r/Python community (meta discussions), Python news, projects, or anything else Python-related!\n\n## How it Works:\n\n1. **Open Mic**: Share your thoughts, questions, or anything you'd like related to Python or the community.\n2. **Community Pulse**: Discuss what you feel is working well or what could be improved in the /r/python community.\n3. **News & Updates**: Keep up-to-date with the latest in Python and share any news you find interesting.\n\n## Guidelines:\n\n* All topics should be related to Python or the /r/python community.\n* Be respectful and follow Reddit's [Code of Conduct](https://www.redditinc.com/policies/content-policy).\n\n## Example Topics:\n\n1. **New Python Release**: What do you think about the new features in Python 3.11?\n2. **Community Events**: Any Python meetups or webinars coming up?\n3. **Learning Resources**: Found a great Python tutorial? Share it here!\n4. **Job Market**: How has Python impacted your career?\n5. **Hot Takes**: Got a controversial Python opinion? Let's hear it!\n6. **Community Ideas**: Something you'd like to see us do? tell us.\n\nLet's keep the conversation going. Happy discussing! 🌟"}
{"instruction": "pyauto_desktop: Benchmarks, window controls, OCR", "input": "", "output": "pyauto_desktop: Benchmarks, window controls, OCR\nI have just released a major update to my pyauto\\_desktop module. Below is the list of new features introduced:\n\n# Optical character recognition\n\nI have added OCR support to my pyauto\\_desktop module, you can now detect text on your screen and automate it.\n\nExample of the inspector at work: [https://i.imgur.com/TqiXLWA.gif](https://i.imgur.com/TqiXLWA.gif)\n\n# Window Control:\n\nYou can now control program windows like minimize, maximize, move, focus and much more!\n\n# Benchmarks:\n\n**1. Standard UI Match**\n\n*Settings: 56x56 Template | Pyramid=True | Grayscale=False | Conf=0.95*\n\n|**Function**|**Library**|**FPS**|**Time (ms)**|**Speedup**|\n|:-|:-|:-|:-|:-|\n|`locateOnScreen`|PyAutoGUI|5.55|180ms|—|\n|`locateOnScreen`|**pyauto\\_desktop**|**23.35**|**42ms**|**4.2x**|\n|`locateAllOnScreen`|PyAutoGUI|5.56|180ms|—|\n|`locateAllOnScreen`|**pyauto\\_desktop**|**24.14**|**41ms**|**4.3x**|\n\n**2. Max Performance (Grayscale)**\n\n*Settings: 56x56 Template | Pyramid=True | Grayscale=True | Conf=0.95*\n\n|**Function**|**Library**|**FPS**|**Time (ms)**|**Speedup**|\n|:-|:-|:-|:-|:-|\n|`locateOnScreen`|PyAutoGUI|10.27|97ms|—|\n|`locateOnScreen`|**pyauto\\_desktop**|**27.13**|**36ms**|**2.6x**|\n|`locateAllOnScreen`|PyAutoGUI|10.20|98ms|—|\n|`locateAllOnScreen`|**pyauto\\_desktop**|**27.01**|**37ms**|**2.6x**|\n\n**3. Small Image / Raw Search (No Scaling)**\n\n*Settings: 24x24 Template | Pyramid=False | Grayscale=False | Conf=0.95*\n\n|**Function**|**Library**|**FPS**|**Time (ms)**|**Speedup**|\n|:-|:-|:-|:-|:-|\n|`locateOnScreen`|PyAutoGUI|6.08|164ms|—|\n|`locateOnScreen`|**pyauto\\_desktop**|**6.74**|**148ms**|**1.1x**|\n|`locateAllOnScreen`|PyAutoGUI|6.14|162ms|—|\n|`locateAllOnScreen`|**pyauto\\_desktop**|**7.12**|**140ms**|**1.2x**|\n\n# What My Project Does\n\nIt allows you to create shareable image or coordinate based automation regardless of resolution or dpr.\n\nIt features:\n\\- **Built-in GUI Inspector** to snip, edit, test, and generate code.\n\\- Uses `Session` logic to scale coordinates & images automatically.\n\\- **Up to 5x Faster.** Uses `mss` & Pyramid Template Matching & Image caching.\n\\- `locateAny` / `locateAll` built-in. Finds the first or all matches from a list of images.\n\\- OCR & Window control\n\n# Target Audience\n\nProgramer who need to automate programs they don't have backend access to and aren't browser-based.\n\nYou can install it here: [pyauto-desktop · PyPI](https://pypi.org/project/pyauto-desktop/)\nCode and Documentation: [pyauto-desktop: github](https://github.com/Omar-F-Rashed/pyauto-desktop)"}
{"instruction": "I patched Chromium because no Python library could reliably pass a single CAPTCHA", "input": "", "output": "I patched Chromium because no Python library could reliably pass a single CAPTCHA\nI had a CRM at work with no API, so I automated it with Playwright. reCAPTCHA scored every stealth library I tried at 0.1. I needed 0.7. None of them got through.\nSo I patched Chromium's C++ source code. 26 modifications compiled into the binary. Then wrapped it in Python so nobody else has to:\n\n    pip install cloakbrowser\n\n    from cloakbrowser import launch\n    browser = launch()  # downloads patched binary on first run\n    page = browser.new_page()\n    page.goto(\"https://whatever-blocks-you.com\")\n\n\nSame Playwright API. Binary auto-downloads for your platform. reCAPTCHA went from 0.1 to 0.9\n\n\\*\\*What My Project Does\\*\\*\nDrop-in Playwright replacement backed by a patched Chromium 145 binary with 26 source-level fingerprint patches. `pip install cloakbrowser`, the binary auto-downloads, gets SHA-256 verified and cached locally. Works on Linux x64, macOS (ARM + Intel) and Windows x64.\n\nWhat it passes:\n\\- reCAPTCHA v3: \\*\\*0.9\\*\\* (server-verified)\n\\- Cloudflare Turnstile: pass (managed + non-interactive)\n\\- BrowserScan, FingerprintJS, deviceandbrowserinfo: all clean\n\\- `navigator.webdriver: false`\n\\- CDP detection: not detected\n\\- TLS fingerprint: identical to real Chrome\n\nDon't take my word for it: `docker run --rm cloakhq/cloakbrowser cloaktest`\nruns the full stealth test suite against live detection sites.\n\nThe Python side handles cross-platform binary management with mirror failover, background auto-updates in a daemon thread, and persistent profiles that keep cookies across sessions. 169 pytest tests, community PRs already merged.\n\nGitHub: [https://github.com/CloakHQ/CloakBrowser](https://github.com/CloakHQ/CloakBrowser)\nPyPI: `pip install cloakbrowser`\n\n\\*\\*Target Audience\\*\\*\nPython developers doing browser automation who hit bot detection. Not just scraping, also testing behind logins, monitoring dashboards, running AI agent frameworks like browser-use or Crawl4AI that use Playwright internally.\n\nNot a scraping stack. No proxy rotation, no CAPTCHA solving. CAPTCHAs don't appear because detection sites score it as a real browser.\n\n\\*\\*Comparison\\*\\*\nTools like playwright-stealth inject JavaScript overrides. undetected-chromedriver patches config flags (and has 1,100+ open issues). Patchright patches the automation protocol. CloakBrowser patches the browser itself, fingerprints baked in at compile time. TLS matches real Chrome because it IS Chrome, just with different internals.\n\nIt handles most things I've thrown at it. `pip install cloakbrowser` and see if yours case is the exception."}
{"instruction": "Blog: Supporting Notebooks in a Python Language Server", "input": "", "output": "Blog: Supporting Notebooks in a Python Language Server\nJupyter notebooks have become an essential tool for Python developers. Their interactive, cell-based workflow makes them ideal for rapid prototyping, data exploration, and scientific computing: areas where you want to tweak a small part of the code and see the updated results inline, without waiting for the whole program to run. Notebooks are the primary way many data scientists and ML engineers write Python, and interactive workflows are highlighted in new data science oriented IDEs like [Positron](https://positron.posit.co/).\n\nBut notebooks have historically been second-class citizens when it comes to IDE features. Language servers, which implement the [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) to provide features like go-to-definition, hover, and diagnostics across editors, were designed with regular source files in mind. The language server protocol did not include notebook synchronization methods until five years after it was created, and the default Jupyter Notebook experience is missing many of the aforementioned IDE features.\n\nIn this post, we'll discuss how language servers have been adapted to work with notebooks, how the LSP spec evolved to support them natively, and how we implemented notebook support in [Pyrefly](https://pyrefly.org).\n\nRead the full blog here: https://pyrefly.org/blog/notebook/"}
{"instruction": "I built a library for safe nested dict traversal with pattern matching", "input": "", "output": "I built a library for safe nested dict traversal with pattern matching\n**What My Project Does**\n\ndotted is a library for safe nested data traversal with pattern matching. Instead of chaining `.get()` calls or wrapping everything in try/except:\n\n    # Before\n    val = d.get('users', {}).get('data', [{}])[0].get('profile', {}).get('email')\n\n    # After\n    val = dotted.get(d, 'users.data[0].profile.email')\n\nIt supports wildcards, regex patterns, filters with boolean logic, in-place mutation, and inline transforms:\n\n    import dotted\n\n    # Wildcards - get all emails\n    dotted.get(d, 'users.data[*].profile.email')\n    # → ('[EMAIL]', '[EMAIL]')\n\n    # Regex patterns\n    dotted.get(d, 'users./.*_id/')\n    # → matches user_id, account_id, etc.\n\n    # Filters with boolean logic\n    dotted.get(users, '[status=\"active\"&!role=\"admin\"]')\n    # → active non-admins\n\n    # Mutation\n    dotted.update(d, 'users.data[*].verified', True)\n    dotted.remove(d, 'users.data[*].password')\n\n    # Inline transforms\n    dotted.get(d, 'price|float')  # → 99.99\n\nOne neat trick - check if a field is **missing** (not just None):\n\n    data = [\n        {'name': 'alice', 'email': '[EMAIL]'},\n        {'name': 'bob'},  # no email field\n        {'name': 'charlie', 'email': None},\n    ]\n\n    dotted.get(data, '[!email=*]')   # → [{'name': 'bob'}]\n    dotted.get(data, '[email=None]') # → [{'name': 'charlie', 'email': None}]\n\n**Target Audience**\n\nProduction-ready. Useful for anyone working with nested JSON/dict structures - API responses, config files, document databases. I use it in production for processing webhook payloads and navigating complex API responses.\n\n**Comparison**\n\n| Feature | dotted | glom | jmespath | pydash |\n|---------|--------|------|----------|--------|\n| Safe traversal | ✅ | ✅ | ✅ | ✅ |\n| Familiar dot syntax | ✅ | ❌ | ❌ | ✅ |\n| Regex patterns | ✅ | ❌ | ❌ | ❌ |\n| In-place mutation | ✅ | ✅ | ❌ | ✅ |\n| Filter negation | ✅ | ❌ | ❌ | ❌ |\n| Inline transforms | ✅ | ✅ | ❌ | ✅ |\n\n**Built with pyparsing** - The grammar is powered by [pyparsing](https://github.com/pyparsing/pyparsing), an excellent library for building parsers in pure Python. If you've ever wanted to build a DSL, it's worth checking out.\n\nGitHub: https://github.com/freywaid/dotted\nPyPI: `pip install dotted-notation`\n\nWould love feedback!"}
{"instruction": "Two high-performance tools for volatility & options research", "input": "", "output": "Two high-performance tools for volatility & options research\nHi everyone,\n\nI wanted to share two projects I built during my time in quantitative equity research (thesis + internship) and recently refactored with performance and usability in mind. Both are focused on financial research and are designed to combine Python usability with C/Cython performance.\n\n# Projects\n\n1. **Volatility decomposition from high-frequency data**: Implements methods to decompose realised volatility into continuous and jump components using high-frequency data.\n\n2. **Option implied moments**: Extracts ex-ante measures such as implied volatility, skewness, and kurtosis from equity option prices.\n\nThe core computations are written in C/Cython for speed and exposed through Python wrappers for ease of use. Technical details can be found in the README to a great extent, and all relevant articles are referenced in there as well.\n\n# Target Audience\n\n* Quant researchers / traders\n* People working with financial data\n* Anyone interested in building high-performance Python extensions\n\nI'd love to hear everyone's thoughts as well as constructive feedback and criticism. They’re not packaged on PyPI yet, but I’d be happy to do that if there’s interest.\n\n# Links\n\n* Volatility decomposition: [https://github.com/justkroft/vol\\_decomposition](https://github.com/justkroft/vol_decomposition)\n* Option implied moments: [https://github.com/justkroft/option-implied-moments](https://github.com/justkroft/option-implied-moments)\n\nMany thanks!"}
{"instruction": "I built a DRF-inspired framework for FastAPI and published it to PyPI — would love feedback", "input": "", "output": "I built a DRF-inspired framework for FastAPI and published it to PyPI — would love feedback\nHey everyone,\n\nI just published my first open source library to PyPI and wanted to share it here for feedback.\n\n**How it started:** I moved from Django to FastAPI a while back. FastAPI is genuinely great — fast, async-native, clean. But within the first week I was already missing Django REST Framework. Not Django itself, just DRF.\n\nThe serializers. The viewsets. The routers. The way everything just had a *place*. With FastAPI I kept rewriting the same structural boilerplate over and over and it never felt as clean.\n\nI looked around for something that gave me that DRF feel on FastAPI. Nothing quite hit it. So I built it myself.\n\n**What FastREST is:** DRF-style patterns running on FastAPI + SQLAlchemy async + Pydantic v2. Same mental model, modern async stack.\n\nIf you've used DRF, this should feel like home:\n\npython\n\n    class AuthorSerializer(ModelSerializer):\n        class Meta:\n            model = Author\n            fields = [\"id\", \"name\", \"bio\"]\n\n    class AuthorViewSet(ModelViewSet):\n        queryset = Author\n        serializer_class = AuthorSerializer\n\n    router = DefaultRouter()\n    router.register(\"authors\", AuthorViewSet, basename=\"author\")\n\nFull CRUD + auto-generated OpenAPI docs. No boilerplate.\n\nYou get ModelSerializer, ModelViewSet, DefaultRouter, permission\\_classes, u/action decorator — basically the DRF API you already know, just async under the hood.\n\n**Where it stands:** Alpha (v0.1.0). The core is stable and I've been using it in my own projects. Pagination, filtering, and auth backends are coming — but serializers, viewsets, routers, permissions, and the async test client are all working today.\n\n**What I'm looking for:**\n\n* Feedback from anyone who's made the same Django → FastAPI switch\n* Bug reports or edge cases I haven't thought of\n* Honest takes on the API design — what feels off, what's missing\n\nEven a \"you should look at X, it already does this\" is genuinely useful at this stage.\n\n`pip install fastrest`\n\nGitHub: [https://github.com/hoaxnerd/fastrest](https://github.com/hoaxnerd/fastrest)\n\nThanks 🙏"}
{"instruction": "Seeking a CPython internals expert to land asyncio Guest Mode (PR #145343) together", "input": "", "output": "Seeking a CPython internals expert to land asyncio Guest Mode (PR #145343) together\nHi everyone,\n\nI’ve put significant research into building a Guest Mode for asyncio to natively integrate with any OS or GUI event loop.\n\nThe architecture is solid and my PR is open. I really want to contribute this to the community because it solves a major integration pain point.\n\nHowever, I’ve hit a bottleneck: CPython core devs are asking deep questions that exceed my current knowledge of Python internals.\n\nI'm looking for an expert in CPython internals to team up, help answer these specific questions, and get this merged.\n\nPR: [github.com/python/cpython/pull/145343](http://github.com/python/cpython/pull/145343)\n\nPOC: [github.com/congzhangzh/asyncio-guest](http://github.com/congzhangzh/asyncio-guest)\n\nRef: [https://www.electronjs.org/blog/electron-internals-node-integration](https://www.electronjs.org/blog/electron-internals-node-integration)\n\nPlease DM me if you can help push this over the finish line!"}
{"instruction": "GoPDFSuit – A JSON-based PDF engine with drag-and-drop layouts. Should I use LaTeX or Typst?", "input": "", "output": "GoPDFSuit – A JSON-based PDF engine with drag-and-drop layouts. Should I use LaTeX or Typst?\nHey r/Python,\n\nI’ve been working on GoPDFSuit, a library designed to move away from the \"HTML-to-PDF\" struggle by using a strictly JSON-based schema for document generation.\n\nThe goal is to allow developers to build complex PDF layouts using structured data they already have, paired with a drag-and-drop UI for adjusting component widths and table structures.\n\n**The Architecture**\n\n* Schema: Pure JSON (No need to learn a specific templating language like Jinja2 or Mako).\n* Layout: Supports dynamic draggable widths for tables and nested components.\n* Current State: Fully functional for business reports, invoices, and data sheets.\n\n**Technical Challenge: Math Implementation**\n\nI’m currently at a crossroads for implementing mathematical formula rendering within the JSON strings. Since this is built for a Python-friendly ecosystem, I’m weighing two options:\n\n1. LaTeX: The \"Gold Standard.\" Huge ecosystem, but might be overkill and clunky to escape properly inside JSON strings.\n2. Typst: The modern alternative. It’s faster, has a much cleaner syntax, and is arguably easier for developers to write by hand.\n\nFor those of you handling document automation in Python, which would you rather see integrated? I’m also curious if you see \"JSON-as-a-Layout-Engine\" as a viable alternative to the standard Headless Chrome/Playwright approaches for high-performance PDF generation.\n\nIn case if you want to check the json template demo\n\n**Demo Link** \\- [https://chinmay-sawant.github.io/gopdfsuit/#/editor](https://chinmay-sawant.github.io/gopdfsuit/#/editor)\n\n**Documentation** \\- [https://chinmay-sawant.github.io/gopdfsuit/#/documentation](https://chinmay-sawant.github.io/gopdfsuit/#/documentation)\n\nIt also has **native python bindings** or calling via the API endpoints for the templates."}
{"instruction": "Anyone else's pipelines pulling durabletask? versions 1.4.1–1.4.3 are backdoored", "input": "", "output": "Anyone else's pipelines pulling durabletask? versions 1.4.1–1.4.3 are backdoored\ncaught this today and wanted to flag it here before it gets buried.\n\n[TeamPCP compromised a GitHub account, ](https://thehackernews.com/2026/05/github-investigating-teampcp-claimed.html)found a PyPI publish token sitting in the repo secrets, and used it to push malicious versions of Microsoft's durabletask package. 1.4.1, 1.4.2 and 1.4.3 are all malicious.\n\npayload runs the moment you import it. no errors, nothing that looks off, just silently stealing credentials in the background, cloud provider keys, SSH keys, Docker creds, 1Password and Bitwarden vaults, HashiCorp Vault secrets, shell history. On AWS it propagates to other EC2 instances via SSM. Kubernetes environments get it through kubectl exec.\n\n417k downloads a month on this package. GitHub is also investigating a separate claimed breach of \\~4,000 of their internal repos from the same group, apparently stemming from the same initial access.\n\nThe entry point was a token with too much access sitting in a repo secret. That's it.\n\nIf your pipelines pulled durabletask recently, treat those machines as fully compromised. Rotate everything, don't just remove the package.\n\nHas anyone already run into this? how wide the impact is."}
{"instruction": "Pycon 2026 in Aveiro", "input": "", "output": "Pycon 2026 in Aveiro\nBelow is the link for Python enthusiasts and programmers/anyone interested in the Pycon 2026 event, which will take place in Aveiro from September 3rd to 5th!\n\nhttps://2026.pycon.pt/"}
{"instruction": "pydynox: DynamoDB ORM with Rust core", "input": "", "output": "pydynox: DynamoDB ORM with Rust core\n    I built a DynamoDB ORM called pydynox. The core is written in Rust for speed.\n\n\n    I work with DynamoDB + Lambda a lot and got tired of slow serialization in Python, so I moved that part to Rust.\n\n\n    ```python\n    class User(Model):\n        model_config = ModelConfig(table=\"users\")\n        pk = String(hash_key=True)\n        name = String()\n\n\n    user = User(pk=\"USER#123\", name=\"John\")\n    user.save()\n\n\n    user = await User.get(pk=\"USER#123\")\n    ```\n\n\n    Has the usual stuff: batch ops, transactions, GSI, Pydantic, TTL, encryption, compression, async. Also added S3Attribute for large files (DynamoDB has a 400KB limit, so you store the file in S3 and metadata in DynamoDB).\n\n\n    Been using it in production for a few months now. Works well for my use cases but I'm sure there are edge cases I haven't hit yet.\n\n\n    Still pre-release (0.12.0). Would love to hear what's missing or broken. If you use DynamoDB and want to try it, let me know how it goes.\n\n\n    https://github.com/leandrodamascena/pydynox\n\n\n    **What my project does**\n\n\n    It's an ORM for DynamoDB. You define models as Python classes and it handles serialization, queries, batch operations, transactions, etc. The heavy work (serialization, compression, encryption) runs in Rust via PyO3.\n\n\n    **Target audience**\n\n\n    People who use DynamoDB in Python, especially in AWS Lambda where performance matters. It's in pre-release but I'm using it in production.\n\n\n    **Comparison**\n\n\n    The main alternative is PynamoDB. pydynox has a similar API but uses Rust for the hot path. Also has some extras like S3Attribute for large files, field-level encryption with KMS, and compression built-in."}
{"instruction": "Building a web game", "input": "", "output": "Building a web game\nHey everyone, I'm a physical game developer looking to port our card game to a website format. I know surface level python and Javascript, but was wondering what the recommended framework would be for getting started.\n\nThis will be my first proper app, so any tips in any direction is appreciated!"}
{"instruction": "Contribution to pyperf", "input": "", "output": "Contribution to pyperf\nI am recently came across the library pyperf because I have to benchmark my changes in a certain open source project to add metrics to the PR I was creating for the changes, but one thing I feel off is types, I don't know why but pyperf has lot of unknown types which is kind of weird so I was planning to contribute to it to make it a little bit better typed.\n\nSo I am wondering do projects like pyperf which comes under pdf accept contribution in generally? If there are any maintainers/contributors of pyperf here then then could answer my question.\n\nThanks in advance.\n\nMy Dev Environment\n\nOS: Windows\n\nType Checker: Pyrefly"}
{"instruction": "I'm new to this world— :)", "input": "", "output": "I'm new to this world— :)\nHey guys, I'm new to Python and starting this whole programming world completely from scratch. I'm watching videos and studying other topics so I can work in this field. My question is: what can I practice with? I downloaded Visual Studio Code, but I don't know what I can do to practice."}
{"instruction": "Generating a tidy HTML report in Python", "input": "", "output": "Generating a tidy HTML report in Python\nI’m shifting from R to PythonIs there a knit markdown version or similar kind for generating a tidy html report in Python?"}
{"instruction": "Python Version in Production ?", "input": "", "output": "Python Version in Production ?\n3.12 / 3.13 / 3.14 (Stable)\n\nSo in production, which version of Python are you using? Apparently I'm using 3.12, but I'm thinking off upgrading to 3.13 What's the main difference? What version are you using for your production in these cases?"}
{"instruction": "Python Web Application Hosting Options", "input": "", "output": "Python Web Application Hosting Options\nThe question is more about hosting for hobby project. And obviously, pricing plays biggest role here.\n\nI never had such combination: Hobby project + web application + python. Js ecosystem has generous free tier hosting, in company I never worried about budgeting for hosting.\n\nSo what are some of the options here?"}
{"instruction": "Python Unplugged on PyTV", "input": "", "output": "Python Unplugged on PyTV\n**Check our this Free Online Python Conference on March 4**\n\nJoin us for a full day of live Python talks!\n\n[JetBrains](https://www.jetbrains.com/) is hosting \"*Python Unplugged on PyTV*\" – a free online conference bringing together people behind the tools and libraries you use every day, and the communities that support them.\n\nLive on YouTube\nMarch 4, 2026\n11:00 am – 6:30 pm CET\n\nExpect 6+ hours on core Python, web development, data science, ML, and AI.\n\nThe event features:\n\\- **Carol Willing** – JupyterLab core developer\n\\- **Paul Everitt** – Developer Advocate at JetBrains\n\\- **Sheena O’Connell** – PSF Board Member\n\\- *Other people you know*\n\nGet the best of Python, straight to your living room.\n\nSave the date: [https://lp.jetbrains.com/python-unplugged/](https://lp.jetbrains.com/python-unplugged/)"}
{"instruction": "A tiny Python networking library focused on simplicity and fun", "input": "", "output": "A tiny Python networking library focused on simplicity and fun\nHey r/Python 👋\nI’m building Veltix, a small Python networking library with a simple goal:\nmake it easy (and fun) to experiment with networking without rewriting socket and threading boilerplate every time.\nVeltix is currently focused on:\na very small and clear API\neasy multithreaded TCP clients and servers\nmessage-based communication on top of TCP\nlearning, prototyping, and experimenting\nBeyond learning, the long-term goal is also to provide strong security and performance:\nplanned Perfect Forward Secrecy\nmodern crypto primitives (ChaCha20, X25519, Ed25519)\na future Rust-based core for better performance and safety, exposed through a clean Python API\nThese parts are not fully implemented yet, but the architecture is being designed with this direction in mind.\nI’d really appreciate feedback on:\nAPI clarity\nwhether this approach makes sense\nexpectations for a “simple but secure” networking library\nGitHub: [https://github.com/NytroxDev/Veltix](https://github.com/NytroxDev/Veltix)\nThanks for reading 🙂"}
{"instruction": "Python optimization", "input": "", "output": "Python optimization\nI’m working on a Python pipeline with two quite different parts.\n\nThe first part is typical tabular data processing: joins, aggregations, cumulative calculations, and similar transformations.\n\nThe 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.\n\nI’m not looking for code-specific debugging, but rather for architectural advice on the best way to handle this kind of workload efficiently\n\nI’d like to improve performance, but I don’t want to start by assuming there is only one correct solution.\n\nMy question is: for a problem like this, which approaches or frameworks would you recommend evaluating?\n\nI must use Python"}
