Transforming code into Beautiful, Idiomatic Python by Raymond Hettinger
Learn to take better advantage of Python's best features and improve existing code through a series of code transformations, "When you see this, do that instead."
tradi:onal index manipula:on with Python’s core looping idioms • Learn advanced techniques with for-‐else clauses and the two argument form of iter() • Improve your craGmanship and aim for clean, fast, idioma:c Python code
colors = ['red', 'green', 'blue', 'yellow'] n = min(len(names), len(colors)) for i in range(n): print names[i], '-->', colors[i] for name, color in zip(names, colors): print name, '-->', color for name, color in izip(names, colors): print name, '-->', color
found = False for i, value in enumerate(seq): if value == tgt: found = True break if not found: return -1 return i def find(seq, target): for i, value in enumerate(seq): if value == tgt: break else: return -1 return i
'green', 'red'] d = {} for color in colors: if color not in d: d[color] = 0 d[color] += 1 {'blue': 1, 'green': 2, 'red': 3} d = {} for color in colors: d[color] = d.get(color, 0) + 1 d = defaultdict(int) for color in colors: d[color] += 1
= argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-c', '--color') namespace = parser.parse_args([]) command_line_args = {k:v for k, v in vars(namespace).items() if v} d = defaults.copy() d.update(os.environ) d.update(command_line_args) d = ChainMap(command_line_args, os.environ, defaults)
of upda:ng state variables at the same :me • It eliminates an en:re class of errors due to out-‐of-‐order updates • It allows high level thinking: “chunking”
t tmp_y = y + dy * t tmp_dx = influence(m, x, y, dx, dy, partial='x') tmp_dy = influence(m, x, y, dx, dy, partial='y') x = tmp_x y = tmp_y dx = tmp_dx dy = tmp_dy x, y, dx, dy = (x + dx * t, y + dy * t, influence(m, x, y, dx, dy, partial='x'), influence(m, x, y, dx, dy, partial='y'))
from administra:ve logic • Clean, beau:ful tools for factoring code and improving code reuse • Good naming is essen:al. • Remember the Spiderman rule: With great power, comes great respsonsibility!
put too much on one line 2. Don’t break atoms of thought into subatomic par:cles Raymond’s rule: • One logical line of code equals one sentence in English