UP | HOME

python decorators

1. decorators with arguments

example definition

def repeat(num_repeats):
  def repeat_decorator(func):
    def repeat_wrapper(*args, **kwargs):
      for _ in range(num_repeats):
        value = func(*args, **kwargs)
      return value
    return repeat_wrapper
return repeat_decorator

usage

@repeat(num_repeats=4)
def my_func(x):
  print("hello")

1.1. explanation

Think of partial function application (see Currying in Haskell). @repeat takes (num_repeats=4) as an argument. It returns a typical decorator function. The decorator function takes the decorated function as input and returns a new function, which is a wrapper around the decorator function. Subsequent calls to the decorated function now go through the wrapper.

2. source

Created: 2024-07-15 Mon 01:27