pythonアクセラレータ適用シーン完了

2887 ワード

    python                      ,                      ,                         。

1     :
     try-exception python         ,         ,      try-catch     。         .

def get_decorator(errors=(Exception, ), default_value=''):

    def decorator(func):

        def new_func(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except errors, e:
                print "Got error! ", repr(e)
                return default_value

        return new_func

    return decorator

try_except = get_decorator(default_value='default')
a = {}

@try_except
def example1(a):
    return a['b']

@try_except
def example2(a):
    return doesnt_exist()

print example1(a)
print example2(a)
#Got error!  KeyError('b',)
#default
#Got error!  NameError("global name 'doesnt_exist' is not #defined",)
#default

2   
               ,                    。       ,                   。                (       :http://en.wikipedia.org/wiki/Functional_programming),                。

  ,                               ,                    。        (memoizing,http://en.wikipedia.org/wiki/Memoizing),               :

import time
import hashlib
import pickle

cache = {}

def is_obsolete(entry, duration):
    return time.time() - entry['time']> duration

def compute_key(function, args, kw):
    key = pickle.dumps((function.__name__, args, kw))
    return hashlib.sha1(key).hexdigest()

def memoize(duration=10):
    def _memoize(function):
        def __memoize(*args, **kw):
            key = compute_key(function, args, kw)
            # do we have it already ?
            if (key in cache and not is_obsolete(cache[key], duration)):
                print('we got a winner')
                return cache[key]['value']
            # computing
            result = function(*args, **kw)
            # storing the result
            cache[key] = {
                'value': result,
                'time': time.time()
            }
            return result
        return __memoize
    return _memoize


              :

@memoize()
def very_very_very_complex_stuff(a, b):
    # if your computer gets too hot on this calculation
    # consider stopping it
    return a + b

very_very_very_complex_stuff(2, 2)
4
very_very_very_complex_stuff(2, 2)
we got a winner

@memoize(1) # invalidates the cache after 1 second
def very_very_very_complex_stuff(a, b):
    return a + b
very_very_very_complex_stuff(2, 2)
4
very_very_very_complex_stuff(2, 2)
we got a winner
4
cache
{'c2727f43c6e39b3694649ee0883234cf': {'value': 4, 'time': 1199734132.7102251)}
time.sleep(2)
very_very_very_complex_stuff(2, 2)
4
      ‘  ’   ,              ,        。               ,       ,    ,              。  ,                              。