Home > Back-end >  One call to decorator function suppressing the other one
One call to decorator function suppressing the other one

Time:10-11

From the following code

class User:
    def __init__(self, name):
        self.name = name
        self.is_logged_in = False


def is_authenticated_decorator(function):
    print('Decorator called')

    def wrapper(*args, **kwargs):
        user = args[0]
        if user.is_logged_in:
            function(user)

    return wrapper


@is_authenticated_decorator
def create_blog_post(user):
    print(f"This is {user.name}'s new blog post")


user_1 = User('John')
create_blog_post(user_1)  # 1

user_1.is_logged_in = True
create_blog_post(user_1)  # 2

I expected the output as

Decorator called
Decorator called
This is John's new blog post

Instead, I am getting the output as

Decorator called
This is John's new blog post

When I comment out the statement marked as #2, I am getting the following output

Decorator called

Why is this output getting suppressed in the presence of #2?

CodePudding user response:

is_authenticated_decorator is only called once when the function is given to the decorator. It's wrapper that's called multiple times. To see each time the function is called, the print should be in the wrapper that's eventually bound to the name create_blog_post.

  • Related