Source code for pylinac.core.decorators

import functools
import time
import weakref


[docs]def timethis(func): """Report execution time of function.""" @functools.wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, f'took {end-start:3.2f}s') return result return wrapper
[docs]def lru_cache(*lru_args, **lru_kwargs): """https://stackoverflow.com/a/33672499""" def decorator(func): @functools.wraps(func) def wrapped_func(self, *args, **kwargs): # We're storing the wrapped method inside the instance. If we had # a strong reference to self the instance would never die. self_weak = weakref.ref(self) @functools.wraps(func) @functools.lru_cache(*lru_args, **lru_kwargs) def cached_method(*args, **kwargs): return func(self_weak(), *args, **kwargs) setattr(self, func.__name__, cached_method) return cached_method(*args, **kwargs) return wrapped_func return decorator