Expert Python Programing
cheatsheet
Chapter1
Chapter2
def fibonacci(): a, b = 0, 1 while True: yield b a, b = b, a + bimport time def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s...' % n) time.sleep(.1) r = '200 OK' def produce(c): next(c) n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close() if __name__=='__main__': c = consumer() produce(c)from time import time def timer(function): def wrapper(*args, **kwargs): before = time() result = function(*args, **kwargs) after = time() print('Run time is %s' % (after - before)) return result return wrapper @timer def add_dec(x, y=10): return x + y @timer def sub_dec(x, y=10): return x - y
from sqlite3 import connect from contextlib import contextmanager @contextmanager def temptable(cur): cur.execute('create table points(x int, y int)') print('created table') try: yield finally: cur.execute('drop table points') print('dropped table') with connect('test.db') as conn: cur = conn.cursor() with temptable(cur): cur.execute('insert into points (x, y) values(1, 1)') cur.execute('insert into points (x, y) values(1, 2)') cur.execute('insert into points (x, y) values(2, 1)') cur.execute('insert into points (x, y) values(2, 2)') for row in cur.execute("select x, y from points"): print(row)
Chapter4
Chapter13
异步编程
Last updated
Was this helpful?