|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | + |
| 4 | +def substitute(a_function): |
| 5 | + """return a different function than the one supplied""" |
| 6 | + def new_function(*args, **kwargs): |
| 7 | + return "I'm not that other function" |
| 8 | + return new_function |
| 9 | + |
| 10 | + |
| 11 | +def add(a, b): |
| 12 | + print "Function 'add' called with args: %r" % locals() |
| 13 | + result = a + b |
| 14 | + print "\tResult --> %r" % result |
| 15 | + return result |
| 16 | + |
| 17 | + |
| 18 | +def logged_func(func): |
| 19 | + def logged(*args, **kwargs): |
| 20 | + print "Function %r called" % func.__name__ |
| 21 | + if args: |
| 22 | + print "\twith args: %r" % (args, ) |
| 23 | + if kwargs: |
| 24 | + print "\twith kwargs: %r" % kwargs |
| 25 | + result = func(*args, **kwargs) |
| 26 | + print "\t Result --> %r" % result |
| 27 | + return result |
| 28 | + return logged |
| 29 | + |
| 30 | + |
| 31 | +def simple_add(a, b): |
| 32 | + return a + b |
| 33 | + |
| 34 | + |
| 35 | +class Memoize: |
| 36 | + """ |
| 37 | + memoize decorator from avinash.vora |
| 38 | + http://avinashv.net/2008/04/python-decorators-syntactic-sugar/ |
| 39 | + """ |
| 40 | + def __init__(self, function): # runs when memoize class is called |
| 41 | + self.function = function |
| 42 | + self.memoized = {} |
| 43 | + |
| 44 | + def __call__(self, *args): # runs when memoize instance is called |
| 45 | + try: |
| 46 | + return self.memoized[args] |
| 47 | + except KeyError: |
| 48 | + self.memoized[args] = self.function(*args) |
| 49 | + return self.memoized[args] |
| 50 | + |
| 51 | + |
| 52 | +@Memoize |
| 53 | +def sum2x(n): |
| 54 | + return sum(2 * i for i in xrange(n)) |
| 55 | + |
| 56 | +import time |
| 57 | + |
| 58 | + |
| 59 | +def timed_func(func): |
| 60 | + def timed(*args, **kwargs): |
| 61 | + start = time.time() |
| 62 | + result = func(*args, **kwargs) |
| 63 | + elapsed = time.time() - start |
| 64 | + print "time expired: %s" % elapsed |
| 65 | + return result |
| 66 | + return timed |
| 67 | + |
| 68 | +@timed_func |
| 69 | +@Memoize |
| 70 | +def sum2x(n): |
| 71 | + return sum(2 * i for i in xrange(n)) |
0 commit comments