Home/Learn/Python A–Z/Modern Idioms — Walrus, Unpacking, Enumerate Patterns & EAFP

Modern Idioms — Walrus, Unpacking, Enumerate Patterns & EAFP

Intermediate
Modern Python

The idioms that mark current Python: the walrus operator :=, star-unpacking, dict merging with |, f-string debugging, and choosing EAFP over permission-checking.

Overview

Python evolves, and code style signals fluency. The walrus operator := (3.8) assigns inside expressions — killing the read-check-repeat pattern in loops and comprehensions. Structural unpacking, | dict merge (3.9), f"{x=}" debug strings, and pathlib-first file handling are what reviewers expect in 2026. This chapter consolidates the small idioms that make Python readers instantly trust your code.

The Walrus Operator :=

Assign AND use a value in one expression. Best in while-loops reading chunks, and comprehensions where a computed value is both filtered and kept — compute once, not twice.

:= assigns inside expressions
# while-read loop — before:
# chunk = f.read(8192)
# while chunk:
#     process(chunk)
#     chunk = f.read(8192)

# after — one place, no repetition:
# while chunk := f.read(8192):
#     process(chunk)

import re
line = "marks: 87"
if m := re.search(r"\d+", line):       # assign + test
    print(int(m.group()))               # 87

# Comprehension: compute once, use twice
def expensive(n):
    return n * n + 1

results = [y for n in range(10) if (y := expensive(n)) > 50]
print(results)                          # [65, 82]

# Don't overuse — if it hurts readability, use two lines.

Small Idioms, Big Signal

These micro-patterns replace whole loops: unpacking swap, ternaries, chained membership on sets, get-with-default, and the modern debugging f-string.

The 2026 Python accent
# f-string debugging (3.8+)
total, count = 480, 5
print(f"{total=} {count=} {total/count=:.1f}")
# total=480 count=5 total/count=96.0

# Star-unpacking in calls and literals
def report(*scores): return max(scores)
weekly = [61, 73, 68]
print(report(*weekly, 80))              # 80

# Merge configs (3.9+) — rightmost wins
base = {"retries": 3, "timeout": 10}
override = {"timeout": 30}
cfg = base | override                   # {'retries': 3, 'timeout': 30}

# Conditional assignment patterns
status = "pass" if total >= 200 else "fail"
name = (user_input or "guest").strip().lower()

# EAFP one more time — it's a style marker
counts = {}
for word in "to be or not to be".split():
    counts[word] = counts.get(word, 0) + 1

# Sentinel iteration — read until a marker without a break
# for line in iter(input, "STOP"): ...

Key Points to Remember

  • 1:= assigns within expressions — while (chunk := read()) and match-and-test patterns
  • 2f"{expr=}" prints both the expression and its value — the fastest debugging
  • 3dict | dict merges (3.9+); {**a, **b} works everywhere
  • 4Readable beats clever — use these where they REMOVE noise, not add it

Interview Questions

Sign in to ask Aria
1

What is the walrus operator and where does it genuinely improve code?

MediumFlipkart
2

Show three ways to merge two dicts and their version requirements.

EasyInfosys

Ask Aria about Modern Idioms — Walrus, Unpacking, Enumerate Patterns & EAFP

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…