Writing Functions in Python
Shayne Miel
Software Architect @ Duo Security
def run_three_times(func): def wrapper(*args, **kwargs): for i in range(3): func(*args, **kwargs) return wrapper@run_three_times def print_sum(a, b): print(a + b)print_sum(3, 5)
8
8
8
def run_n_times(func): def wrapper(*args, **kwargs): # How do we pass "n" into this function? for i in range(???): func(*args, **kwargs) return wrapper@run_n_times(3) def print_sum(a, b): print(a + b)@run_n_times(5) def print_hello(): print('Hello!')
def run_n_times(n): """Define and return a decorator"""def decorator(func):def wrapper(*args, **kwargs):for i in range(n): func(*args, **kwargs)return wrapperreturn decorator@run_n_times(3) def print_sum(a, b): print(a + b)
def run_n_times(n): """Define and return a decorator""" def decorator(func): def wrapper(*args, **kwargs): for i in range(n): func(*args, **kwargs) return wrapper return decoratorrun_three_times = run_n_times(3)@run_three_times def print_sum(a, b): print(a + b)@run_n_times(3) def print_sum(a, b): print(a + b)
@run_n_times(3) def print_sum(a, b): print(a + b)print_sum(3, 5)
8
8
8
@run_n_times(5) def print_hello(): print('Hello!')print_hello()
Hello!
Hello!
Hello!
Hello!
Hello!
Writing Functions in Python