1

I'm trying to learn about Python decorators. The guide I'm going through referenced this code:

from time import sleep


def sleep_decorator(function):

    """
    Limits how fast the function is
    called.
    """

    def wrapper(*args, **kwargs):
        sleep(2)
        return function(*args, **kwargs)
    return wrapper


@sleep_decorator
def print_number(num):
    return num

print(print_number(222))

for num in range(1, 6):
    print(print_number(num))

If I'm understanding this correctly, @sleep_decorator essentially runs sleep_decorator(print_number(num)). What I'm struggling to understand is how the print function and for loop below that fits into the whole thing. Are these all also part of the decorator? Or is the @sleep_decorator redefining print_number so that it always runs through the sleep_decorator function?

Eric
  • 95,302
  • 53
  • 242
  • 374
jylny
  • 146
  • 1
  • 1
  • 8
  • 3
    Your last suggestion is the correct one. And no, what it essentially runs is `sleep_decorator(the_undecorated_print_number)(num)`. Note the parentheses. – Eric Feb 13 '17 at 21:39
  • Thank you; the link was helpful was well. Could you explain a little more on the separated (num) component? Why is that not included in under the print_number function? – jylny Feb 13 '17 at 21:47

0 Answers0