Skip to Content
Expert Python Programming - Third Edition
book

Expert Python Programming - Third Edition

by Michał Jaworski, Tarek Ziadé, Cody Jackson
April 2019
Intermediate to advanced
646 pages
16h 48m
English
Packt Publishing
Content preview from Expert Python Programming - Third Edition

Parametrizing decorators

In real usage scenarios, there is often a need to use decorators that can be parameterized. When the function is used as a decorator, then the solution is simple – a second level of wrapping has to be used. Here is a simple example of the decorator that repeats the execution of a decorated function the specified number of times every time it is called:

def repeat(number=3): 
    """Cause decorated function to be repeated a number of times. 
     
    Last value of original function call is returned as a result.
     :param number: number of repetitions, 3 if not specified """ def actual_decorator(function): def wrapper(*args, **kwargs): result = None for _ in range(number): result = function(*args, **kwargs) return result return wrapper ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert Python Programming - Fourth Edition

Expert Python Programming - Fourth Edition

Michał Jaworski, Tarek Ziade, Tarek Ziadé

Publisher Resources

ISBN: 9781789808896Other