def __call__(self, func, on_success=on_success, on_failure=on_failure, on_closing=on_closing): # every decorated function has its own independent thread counter func.counter = itertools.count(1) func.on_success = on_success func.on_failure = on_failure func.on_closing = on_closing return decorator(self.call, func)
def restricted(user_class): def restricted(func, *args, **kw): "Restrict access to a given class of users" userclass = get_userclass() if issubclass(userclass, user_class): return func(*args, **kw) else: raise PermissionError( '%s does not have the permission to run %s!' % (userclass.__name__, func.__name__)) return decorator(restricted)
def blocking(not_avail): def blocking(f, *args, **kw): if not hasattr(f, "thread"): # no thread running def set_result(): f.result = f(*args, **kw) f.thread = threading.Thread(None, set_result) f.thread.start() return not_avail elif f.thread.isAlive(): return not_avail else: # the thread is ended, return the stored result del f.thread return f.result return decorator(blocking)
def memoize(f): f.cache = {} return decorator(_memoize, f)
def trace(f): return decorator(_trace, f)
def decorate(cls): for attr in cls.__dict__: # there's propably a better way to do this if callable(getattr(cls, attr)): setattr(cls, attr, decorator(getattr(cls, attr))) return cls