Decorators that take arguments

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
Writing Functions in Python

run_n_times()

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!')
Writing Functions in Python

A decorator factory

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 decorator
@run_n_times(3) def print_sum(a, b): print(a + b)
Writing Functions in Python
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 decorator

run_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)
Writing Functions in Python

Using run_n_times()

@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

Let's practice!

Writing Functions in Python

Preparing Video For Download...