### partial #################################################################### from functools import partial, wraps import sys import string def add(x, y): """Adds two numbers x and y together""" return x + y def mult(x, y): """Multiplies two numbers x and y together""" return x * y def say(string, stream=sys.stdout): """Prints string to stream (default sys.stdout)""" print >>stream, string splitcommas = partial(string.split, sep=",") splitspaces = partial(string.split, sep=" ") ### wraps ###################################################################### def mydeco(f): @wraps(f) def inner(*args, **kwargs): print "Calling decorated %s with args: %s, %s" % (f.__name__, args, kwargs) return f(*args, **kwargs) return inner @mydeco def factorial(n): """Recursively compute simple factorial (n!)""" if n < 1: return 1 else: return n*factorial(n-1) ### conditional expressions #################################################### def show_conditional_expressions(): #before 2.5... x = 20 print x > 0 and "Positive" or "Negative or zero" #relies on short circuiting logic print ["Negative or zero", "Positive"][x > 0] #ugly, and evaluates eagerly #now we can use a conditional expression instead print "Positive" if x > 0 else "Negative or zero" #much better #we can nest them too test_temp = lambda temp: "Above freezing" if temp > 32 else ("Below freezing" if temp < 32 else "At freezing") print 0, "->", test_temp(0) print 10, "->", test_temp(10) print 32, "->", test_temp(32) print 45, "->", test_temp(45) print 100, "->", test_temp(100)