December 2018
Beginner to intermediate
796 pages
19h 54m
English
Let's simplify this example now, going back to a single decorator: max_result. I want to make it so that I can decorate different functions with different thresholds, as I don't want to write one decorator for each threshold. Let's amend max_result so that it allows us to decorate functions specifying the threshold dynamically:
# decorators/decorators.factory.pyfrom functools import wrapsdef max_result(threshold): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if result > threshold: print( 'Result is too big ({0}). Max allowed is {1}.' .format(result, threshold)) return result return wrapper return decorator@max_result(75)def cube(n): return n ** 3print(cube(5))
The preceding ...
Read now
Unlock full access