Nice reminder: if you only care about the top K items, reach for heapq instead of a full sort.
04.12.2025 15:00 — 👍 0 🔁 0 💬 0 📌 0@bbelderbos.bsky.social
Co-founder @pybites.bsky.social. Python developer & coach helping devs level up with project-based learning & modern Python. Start here → https://pybit.es
Nice reminder: if you only care about the top K items, reach for heapq instead of a full sort.
04.12.2025 15:00 — 👍 0 🔁 0 💬 0 📌 0Refactor:
- sorted(..., key=... )[:top_n] ➡️ heapq.nsmallest(top_n, ...)
- sorted(..., key=..., reverse=True)[:top_n] ➡️ heapq.nlargest(top_n, ...)
Same behaviour, but now it’s O(n log k) instead of O(n log n) when k << n.
Refactoring win from a Codeflash the other day 👇
I only needed the worst N files / most complex N functions…
but the code was doing a full sort and then [:top_n].
On Python >= 3.10? Long if/elif chains are prime candidates for this.
And seeing match/case so much in Rust, I appreciate it even more in Python now 🐍😍
Refactored a long if/elif ladder into match/case the other day 👇
`case 1 | 2` groups opcodes that share behavior
`case 5 if part2` keeps the extra condition right next to the logic ("flat is better than nested")
Feels more like a clean dispatcher than a pile of conditionals.
What other (more_)itertools gems have you used recently? 💬
02.12.2025 14:00 — 👍 0 🔁 0 💬 0 📌 0Writing your own list chunking helpers? Check out #Python’s `itertools.batched()` that can do this for you 🚀
✅ Works with any iterable.
✅ Handles a smaller final chunk automatically.
✅ Use `strict=True` (Python 3.13+) to raise a `ValueError` when the final batch isn’t full.
👉 Where have Rust (or other language)-inspired patterns improved your Python the most?
01.12.2025 15:00 — 👍 0 🔁 0 💬 0 📌 0--
None of this turns Python into Rust, but borrowing (no pun intended 😄) Rust’s strictness makes your Python code more predictable, easier to refactor, and more pleasant to work in.
Implement them as staticmethods (e.g. `Rectangle.from_tl_and_size(...)`): they stay closer to pure functions tied to the type and avoid some of the subclassing quirks classmethod-based constructors can bring.
01.12.2025 15:00 — 👍 0 🔁 0 💬 1 📌 04️⃣ Fewer subclasses, more factory functions instead of mega-constructors
Use explicit factory methods like `Rectangle.from_tl_and_size(...)` instead of stuffing every variant into `__init__`.
3️⃣ Model variants & legal states explicitly
Use unions and small types to model variants and states: e.g. `Header | Payload | Trailer`, or `ConnectedClient` vs `AuthenticatedClient`.
Less “remember to call this first”, more “the wrong state/variant is impossible by design.”
2️⃣ Small, named types over tuples/dicts
Instead of returning `Tuple[str, str, int]` / `Dict[str, Any]`, create a small type: use a `dataclass` or a `NamedTuple` (immutable, very Rust-y).
Your IDE can better assist you – and it’s much nicer for your future self and your team.
1️⃣ Treat type hints as part of the API
Not just “nice to have”. Rich signatures (`Item`, `Callable`, `Optional`) turn “guess the interface” into “read the types and you’re done”.
I was reading Kobzol’s excellent article “Writing #Python like it’s #Rust”, and it perfectly captures how Rust can upgrade the way you write Python. 💡
Here are some takeaways I keep coming back to:
What’s your favourite “I just changed the data structure and it became instant” moment? 💬
30.11.2025 15:00 — 👍 0 🔁 0 💬 0 📌 0Same logic, single pass, no repeated string rebuilding.
New runtime? About 0.1 seconds. 🔥
Sometimes the biggest performance win isn’t a faster language or clever micro-optimisation – it’s picking the right data structure. 💡
Then we rewrote it using a simple stack 👇
30.11.2025 15:00 — 👍 0 🔁 0 💬 1 📌 0When profiling code we saw:
...
78782697 4.851 0.000 4.851 0.000 {method 'swapcase' of 'str' objects} 78691470 3.541 0.000 3.541 0.000 {method 'append' of 'list' objects}
...
~80 million times × “tiny cost” ≈ many seconds 😅
Our first solution kept iterating over the string and rebuilding it until it stopped changing.
It worked… but took almost 9 seconds.
From ~9 seconds to ~0.1 seconds… just by changing the data structure.
In a recent @Pybites code ensemble session we tackled an Advent of Code puzzle where you repeatedly “react” a polymer string by removing adjacent units like aA / Bb.
From messy to clean numbers with `removeprefix` / `removesuffix`
With `removeprefix("$")` and `removesuffix(suffix)` you strip only what you *expect* to be there, then `float(cap) * multiplier` does the rest.
Classic EAFP: try to parse, fall back to `0.0` when the data is junk.
Cool debugging trick I picked up from this article:
Django bulk_update memory issue
blog.pecar.me/django-bulk...
Logging memory usage in #Python using `psutil` - example below 👇
Bonus: comparing list comp vs gen expression 🐍 😍 📈
Watch it on YouTube ▶️ www.youtube.com/watch?v=qkvA...
Or listen to it in your favorite podcast 🎧 app.
Kishan is also a prolific content creator making high-quality and entertaining Python videos + articles.
I hope you enjoy my conversation with Kishan.
• His single 2025 goal of "becoming the best Python developer he could be", inspired by Gary Keller's The ONE Thing.
• How he uses AI in 'hybrid mode'.
• Interesting developer mindset lessons learned.
We spoke about:
• His journey in our PDM program.
• How he managed to ship 3 fully-fledged apps (including publishing his first package to PyPI)
Really enjoyed my chat with Kishan Patel on our @pybites podcast.
27.11.2025 12:17 — 👍 1 🔁 1 💬 1 📌 0We decided to do something different for #BlackFriday
Instead of selling you "content," we're discounting "accountability."
For the first time, we've slashed the price on our #Python Snipster (Intermediate) and Foundations (Beginner) cohorts (30-35% off).
If you enjoy this kind of standard library power, that’s exactly what we practise on our coding platform: small, real-world 🐍 exercises that make patterns like this second nature. 📈
And this week 40% off :)
Join here: pybitesplatform.com