装飾器の使い方と役割

9802 ワード

1.パラメータチェック
2.キャッシュ
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)
			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 __memoize
	return _memoize


3.エージェント
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 won't tell you")
			return function(*args, **kw)
		return __protect
	return _protect

4.コンテキストプロバイダ
from threading import RLock
lock = RLock()

def synchronized(function):
	def _synchronized(*args, **kwargs):
		lock.acquire()
		try:
			return function(*args, **kwargs(
		finally:
			lock.release()
	return _synchronized

@synchronized
def thread_safe():
	pass