| name | hettinger-idiomatic-python |
| description | Write Python code in the style of Raymond Hettinger, Python core developer. Emphasizes beautiful, idiomatic code using iterators, generators, and built-in tools elegantly. Use when transforming code into clean, Pythonic solutions. |
| tags | itertools, collections, decorators, idioms, readability, functional, generators, clean-code, pythonic |
Raymond Hettinger Style Guide
Overview
Raymond Hettinger is a Python core developer famous for his talks on transforming code into beautiful, idiomatic Python. His mantra "There must be a better way!" drives the pursuit of elegant solutions using Python's rich toolkit.
Core Philosophy
"There must be a better way!"
"If you copy-paste code, you're doing it wrong."
"The goal is not to teach Python, but to teach programming using Python."
Hettinger believes Python's beauty lies in its tools—iterators, generators, decorators—and knowing when and how to use them transforms mediocre code into elegant solutions.
Design Principles
-
Use the Right Tool: Python has tools for everything. Find them.
-
Iterate, Don't Index: Let Python handle the iteration machinery.
-
Compose Small Functions: Build complex behavior from simple, reusable pieces.
-
Embrace Generators: Lazy evaluation is memory-efficient and composable.
When Writing Code
Always
- Use
collections module (Counter, defaultdict, deque, namedtuple)
- Use
itertools for iterator algebra
- Use
functools for function composition
- Prefer generators over building lists
- Use descriptive names that read like prose
- Chain operations fluently when appropriate
Never
- Build lists just to iterate over them once
- Write nested loops when
itertools.product works
- Manually implement what
itertools provides
- Use indices when direct iteration works
- Repeat code—abstract it
Prefer
collections.Counter over manual counting
collections.defaultdict over .setdefault()
itertools.chain over nested loops
itertools.groupby over manual grouping
- Generator expressions over list comprehensions (when iterating once)
functools.lru_cache over manual memoization
Code Patterns
The Collections Module
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
from collections import Counter
word_counts = Counter(words)
top_ten = word_counts.most_common(10)
groups = {}
for item in items:
key = get_key(item)
if key not in groups:
groups[key] = []
groups[key].append(item)
from collections import defaultdict
groups = defaultdict(list)
for item in items:
groups[get_key(item)].append(item)
point = (10, 20, 30)
x = point[0]
y = point[1]
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y', 'z'])
point = Point(10, 20, 30)
print(point.x, point.y)
The itertools Module
from itertools import chain, groupby, product, combinations, islice
nested = [[1, 2], [3, 4], [5, 6]]
flat = list(chain.from_iterable(nested))
for a, b in combinations([1, 2, 3, 4], 2):
print(a, b)
for x in xs:
for y in ys:
for z in zs:
process(x, y, z)
for x, y, z in product(xs, ys, zs):
process(x, y, z)
first_ten = list(islice(huge_generator, 10))
data = [('A', 1), ('A', 2), ('B', 3), ('B', 4)]
for key, group in groupby(data, key=lambda x: x[0]):
print(key, list(group))
Generator Excellence
def get_squares(n):
result = []
for i in range(n):
result.append(i ** 2)
return result
def get_squares(n):
for i in range(n):
yield i ** 2
squares = (i ** 2 for i in range(n))
def pipeline(data):
cleaned = (clean(item) for item in data)
validated = (item for item in cleaned if is_valid(item))
transformed = (transform(item) for item in validated)
return transformed
for result in pipeline(huge_dataset):
process(result)
Decorator Patterns
from functools import wraps, lru_cache, partial
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result
return wrapper
def repeat(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def ():
()
Sorting Idioms
students = [('Alice', 85), ('Bob', 90), ('Charlie', 85)]
sorted_students = sorted(students, key=lambda s: (-s[1], s[0]))
from operator import itemgetter, attrgetter
sorted_students = sorted(students, key=itemgetter(1), reverse=True)
sorted_users = sorted(users, key=attrgetter('last_name', 'first_name'))
Mental Model
Hettinger approaches code by asking:
- Is there a built-in for this? Check
collections, itertools, functools first
- Can I use a generator? Process one item at a time, not all at once
- Can I compose existing tools? Chain small operations together
- Would a decorator help? Cross-cutting concerns belong in decorators
Signature Hettinger Moves
- Replace manual loops with
sum(), any(), all(), max(), min()
- Replace index access with
zip(), enumerate(), unpacking
- Replace manual caching with
@lru_cache
- Replace nested loops with
itertools.product
- Replace manual counting with
collections.Counter