import time
import hashlib
import pickle
import threading
#装饰函数缓存应用
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 momoize(duration=10):
def __momoize(function):
def __momoize(*args,**kw):
key = compute_key(function,args,kw)
#是否已经拥有了它?
if(key in cache and not is_obsolete(cache[key],duration)):
print('we got a winner')
return cache[key]['value']
#计算
result =function(*args,**kw)
#保存结果
cache[key] ={
'value':result,
'time':time.time()
}
return result
return __momoize
return __momoize
@momoize(5)
def very_very_complex_stuff(a,b):
#如果在执行计算时计算机过热
#请终止程序
return a + b
# very_very_complex_stuff(1,1)
# very_very_complex_stuff(2,2)
# very_very_complex_stuff(3,3)
# very_very_complex_stuff(4,4)
# print(cache)
# time.sleep(5)
# very_very_complex_stuff(1,1)
# very_very_complex_stuff(2,2)
# very_very_complex_stuff(3,3)
# very_very_complex_stuff(4,4)
# print(cache)
#代理
class User(object):
def __init__(self,roles):
self.roles =roles
class Unauthorized(Exception):
pass
def protect(role):
def _protect(function):
def __protect(*args,**kw):
user = globals().get('user')
if(user is None or role not in user.roles):
raise Unauthorized("I wo'nt tell you")
return function(*args,**kw)
return __protect
return _protect
tarek =User(('admin','user'))
bill =User(('user'))
class Mysecrets(object):
@protect('admin')
def waffle_recipe(self):
print('user tons of butter!')
# these_are = Mysecrets()
# user = tarek
# these_are.waffle_recipe()
#上下文
from threading import RLock
lock =RLock()
def synchronized(function):
def _synchronized(*args,**kw):
lock.acquire()
try:
return function(*args,**kw)
finally:
lock.release()
return _synchronized
@synchronized
def thread_safe():
pass
class ContextIllustration:
def __enter__(self):
print('entering context')
def __exit__(self,exc_type,exc_value,traceback):
print('leaving context')
if exc_type is None:
print('with no error')
else:
print('with an error (%s)'%exc_value)
# with ContextIllustration():
# print('inside')
from contextlib import contextmanager
@contextmanager
def contextillustration():
print('entering context')
try:
yield
except Exception as e:
print('leaving context')
print('with an error (%s)'%e)
raise
else:
print('leaving context')
print('with no error')
with contextillustration():
print('inside')
for number in range(1):
break
else:
print('no break')