# vim: set expandtab ts=4 sw=4 filetype=python: import signal import logging, logging.config from random import choice logging.config.fileConfig("debuglogger.cfg") log = logging.getLogger("debuglogger") companions = ['Sara Jane Smith', 'Leela', 'Rose Tyler'] alphabetized_companions = ['Leela', 'Sara Jane Smith', 'Rose Tyler'] def extract(s): "Return a string to sort by." if ' ' in s: return s.split(' ')[-1] else: return s def companion_compare(a, b): "Use function extract to compare a and b." if extract(a) < extract(b): return -1 elif extract(a) > extract(b): return 1 else: return 0 def f(a, b): "Returns a minus b" return a - b def debuglogger(f): def logged(*args, **kwargs): log.debug("args is %s and kwargs is %s." % (args, kwargs)) results = f(*args, **kwargs) log.debug("results from calling %s is %s." % (f.func_name, results)) return results return logged def add_n(n): "Return a decorator that adds n." def dec(f): "This is the decorator" def h(*args, **kwargs): "This is the decorated version of f" return n + f(*args, **kwargs) return h return dec def A(): for x in 'wash', 'flea dip', 'dry': print x def B(): A() print 'toothbrushing' def B2(): "Like B, but doesn't call A first" print 'toothbrushing' def C(): for x in 'wash', 'dry','hairball medicine': print x def D(): C() print 'A ridiculous haircut' class Pet(object): "Parent for Cat and Dog" def groom(self, package): raise NotImplementedError("subclasses must define this...") class Cat(Pet): "I am a cat" def groom(self, package): print "calling Cat.groom" if isinstance(package, Standard): C() else: D() class Dog(Pet): "I am a dog" def groom(self, package): if isinstance(package, Standard): A() else: B() class Package(object): "Parent of standard and premium" class Standard(Package): "The cheapo way out" class Premium(Package): "You have too much money" def customer_shows_up(): return Cat() def customer_chooses(): return Premium() def returns_sometimes(): "Return immediately (99%) or hang forever (1%)." if choice(range(1, 101)) != 1: return else: i = 1 while "forever": i += 1 if i == 1000000: i = 0 class TimeoutException(Exception): "Indicates that the function has taken too long." def handle_alarm(*args): logging.error("Timeout!") raise TimeoutException(*args) def with_timeout(seconds_to_wait, on_timeout): """ After seconds_to_wait seconds, we interrupt the function and instead call on_timeout. """ def dec(f, *args, **kwargs): # Set the handler for the alarm signal. signal.signal(signal.SIGALRM, handle_alarm) # Schedule an alarm for two seconds in the future. signal.alarm(seconds_to_wait) try: # Call the function. y = f(*args, **kwargs) # If the function returned, then cancel the alarm. signal.alarm(0) # Now return what we got. return y except TimeoutException, ex: on_timeout(ex) return dec def out_of_time(ex): "Clean up and move on." log.debug("We got unlucky.") log.debug("ex.args is %s." % str(ex.args)) __id__ = "$Id: decoratortalk.py 106 2008-07-25 03:45:15Z matt $"