Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1.  
  2. It turns out that decorators "eat" my docs. Luckily functools.wrap is a decorator (you read that right) to fix this!
  3.  
  4. from functools import wraps
  5. def timing(ms):
  6. def fun_wrapper(f):
  7. @wraps(f)
  8. def wrap(*args, **kwargs):
  9. """Decorator to time functions"""
  10. time1 = time.time()
  11. ret = f(*args, **kwargs)
  12. time2 = time.time()
  13. t = (time2 - time1) * 1000.0
  14. if t < ms: t = 0
  15. logging.debug('%s function took %0.3f ms' %
  16. (f.__name__, t))
  17. return ret
  18. return wrap
  19. return fun_wrapper
  20.  
  21. In [9]:
  22. @timing(60)
  23. def factorize(n):
  24. "Return the factors of n"
  25. return [x for x in range(1, n // 2) if n % x == 0] # I've made this a list to make the timing thing work
  26. print(factorize.__doc__)
  27.  
  28. Return the factors of n
  29. Exercise
  30. Write and test a decorator that convert the output of a function from a dictionary to json. After you're done, and if you have more time, add the separators option to the decorator.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement