装饰器用法和作用

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

你可能感兴趣的:(python)