max(1, 2, 3, 4) dict(a=1, b=2) def add(*args): return sum(args) print add(1, 2, 3, 4) def mydict(**kwargs): return kwargs print mydict(a=1, b=2) def render_tag(tagname, **attrs): pairs = ["%s=%s" % (k,v) for k, v in attrs.items()] return "<%s %s/>" % (tagname, " ".join(pairs)) render_tag("input", type="text", name="x", id="x") numbers = [1, 2, 3, 4] print add(*numbers) def add(a, b): return a+b args=[1] kwargs={"b": 2} print add(*args, **kwargs) def call_fun(f, *args, **kwargs): return f(*args, **kwargs) import time def timeit(f): def g(): t0 = time.time() value = f() t1 = time.time() print "took %f seconds" % (t1-t0) return value return g def timepass(): for i in range(10000): for j in range(1000): x = i*j return 0 def timepass2(n): for i in range(n): for j in range(1000): x = i*j return 0 timepass = timeit(timepass) print timepass() import urllib @timeit def wget(url): return urllib.urlopen(url).read() x = wget("http://python.org") %%file bicycle.py mapping = [] before_hooks = [] def request(url): for path, func in mapping: if path == url: for h in before_hooks: h(url) return func() return "404 - Not Found" def route(path): def decorator(f): mapping.append((path, f)) return f return decorator def before_request(f): before_hooks.append(f) return f from bicycle import route, request, before_request import time @route("/hello") def hello(): return "Hello, world" @route("/bye") def bye(): return "Goodbye" @before_request def log(url): print time.asctime(), url if __name__ == "__main__": print "MAIN" print request("/hello") # should print "Hello, world" print request("/bye") print request("/foo") %%file command0.py def command(f): def g(filenames, **kw): lines = readfiles(filenames) #lines = (outline for line in lines # for outline in f(line, **kw)) lines = generate_output(f, lines, **kwargs) printlines(lines) return g def generate_output(f, lines, **kwargs): for line in lines: for outline in f(line, **kwargs): yield outline def readfiles(filenames): for f in filenames: for line in open(f): yield line def printlines(lines): for line in lines: print line.strip("\n") %%file uppercase.py from command0 import command @command def uppercase(line): yield line.upper() if __name__ == "__main__": import sys uppercase(sys.argv[1:]) !python uppercase.py uppercase.py %%file grep.py from command0 import command @command def grep(line, pattern): if pattern in line: yield line if __name__ == "__main__": import sys pattern = sys.argv[1] filenames = sys.argv[2:] grep(filenames, pattern=pattern) !python grep.py def grep.py %%file twice.py from command0 import command @command def twice(line): yield line yield line if __name__ == "__main__": import sys twice(sys.argv[1:]) !python twice.py twice.py code = "x = 1" exec(code) print x eval("1 + 2") env = {"x": 2} eval("x + 2", env)