← Blog

10 Python Tricks I Wish I Knew Earlier

June 12, 2025 · 7 min read · PythonDev

I've been writing Python for about ten years. Every so often I stumble on a feature that makes me wonder how I managed without it. Here are ten of them.

1. The Walrus Operator (:=)

Assign and test in a single expression. Especially handy in while loops:

while chunk := f.read(8192): process(chunk)

2. Structural Pattern Matching

Python 3.10's match statement is more than a switch — it deconstructs data structures cleanly, making command parsers and state machines dramatically more readable.

3. Dataclasses with __slots__

Add slots=True to @dataclass and you get the clarity of a dataclass with the memory efficiency of slots. Free win.

4. functools.cache

Simpler than lru_cache for unbounded memoization. One decorator, no arguments needed.

5. itertools.pairwise

Python 3.10+. Returns overlapping pairs from an iterable. No more zip(lst, lst[1:]).

6. dict | Merge Operator

merged = defaults | overrides — clean dictionary merging without update() or ** unpacking gymnastics.

7. pathlib over os.path

If you're still writing os.path.join, try Path objects. The / operator for joining paths alone is worth the switch.

8. contextlib.suppress

Replace bare try/except/pass blocks with with suppress(FileNotFoundError):. Intent is immediately clear.

9. TypedDict for Typed Dicts

When you need the flexibility of a dict but the safety of type hints, TypedDict is your friend — especially for JSON-shaped data.

10. __init_subclass__

A lighter-weight alternative to metaclasses for registering or validating subclasses. Reach for this before you reach for type.

That's the list. All of these are in the standard library or built-in — no dependencies required. Happy coding.