Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- It turns out that decorators "eat" my docs. Luckily functools.wrap is a decorator (you read that right) to fix this!
- from functools import wraps
- def timing(ms):
- def fun_wrapper(f):
- @wraps(f)
- def wrap(*args, **kwargs):
- """Decorator to time functions"""
- time1 = time.time()
- ret = f(*args, **kwargs)
- time2 = time.time()
- t = (time2 - time1) * 1000.0
- if t < ms: t = 0
- logging.debug('%s function took %0.3f ms' %
- (f.__name__, t))
- return ret
- return wrap
- return fun_wrapper
- In [9]:
- @timing(60)
- def factorize(n):
- "Return the factors of n"
- 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
- print(factorize.__doc__)
- Return the factors of n
- Exercise
- 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