Debugging

def debug(command, my_arg, my_locals):
	global stepping
	global breakpoints

	if command.find(' ') > 0:
		arg = command.split(' ')[1]
	else:
		arg = None

	if command.startswith('s'):
		stepping = True
		return True

def traceit(frame, event, arg):
	global stepping
	global breakpoints

	if event == 'Line':
		if stepping or breaking.has_key(frame.f_lineno):
			resume = False
			while not resume:
				print event, frame.f_lineno, frame.f_code.co_name, frame.f_locals
				command = input_command()
				resume = debug(command, arg, frame.f_locals)
		return traceit

Assertions is the most powerful debugging tool, automating debugging tool.

def test_square_root():
	assert square_root(4) == 2
	assert square_root(g) == 3
	# and so on
import math

def square_root(x):
	assert x >= 0
	y = math.sqrt(x)
	assert y * y == x
	return y

testing square root

import math
random

def square_root(x):
	assert x >= 0
	y = math.sqrt(x)
	assert y * y == x
	return y

for i in range(1, 1000):
	r = random.random() * 10000
	try:
		z = square_root(r)
	except:
		print r, math.sqrt(r) * math.sqrt(r)
		break

print "Done!"
import math
import random

def square_root(x, eps=10e-7):
    assert x >= 0
    y = math.sqrt(x)
    assert abs(y * y - x) < eps
    return y

for i in range(1, 1000):
    r = random.random() * 1000
    z = square_root(r)

print "Done!"
class Time:
	def __init__(self, h = 0, m = 0, s = 0):
		self._hours = h
		self._minutes = m
		self._seconds = s

	def hours(self):
		return self._hours

	def minutes(self):
		return self._minutes

	def seconds(self):
		return self._seconds

	def __repr__(self):
		return "{:2d}{:2d}{:2d}".format(
			self.hours(), self.minutes(), self.seconds())

t = Time(13, 0, 0)
print t