Interview question
How do you stack multiple decorators on a single function, and what order do they execute in? एक function पर multiple decorators कैसे stack करें, और वो किस order में execute होते हैं?
Answer
When stacking decorators, they wrap the function from the BOTTOM up, but the wrapped calls execute from the TOP down when the function is actually invoked.
def decorator_a(func):
def wrapper(*args, **kwargs):
print('A: before')
result = func(*args, **kwargs)
print('A: after')
return result
return wrapper
def decorator_b(func):
def wrapper(*args, **kwargs):
print('B: before')
result = func(*args, **kwargs)
print('B: after')
return result
return wrapper
@decorator_a
@decorator_b
def greet():
print('Hello!')
greet()
# A: before
# B: before
# Hello!
# B: after
# A: after
# This is equivalent to writing:
def greet2():
print('Hello!')
greet2 = decorator_a(decorator_b(greet2))
# decorator_b wraps greet2 FIRST (innermost, closest to the function)
# decorator_a wraps the RESULT of that (outermost)
# Practical example: logging + authentication stacked
def require_auth(func):
def wrapper(*args, **kwargs):
print('Checking authentication...')
return func(*args, **kwargs)
return wrapper
def log_call(func):
def wrapper(*args, **kwargs):
print(f'Calling {func.__name__}')
return func(*args, **kwargs)
return wrapper
@require_auth # runs FIRST (outermost)
@log_call # runs SECOND (closer to the actual function)
def delete_user(user_id):
print(f'Deleting user {user_id}')
delete_user(5)
# Checking authentication...
# Calling delete_user
# Deleting user 5Multiple decorators stack करते समय, वो function को नीचे से ऊपर wrap करते हैं, पर function call होने पर execution ऊपर से नीचे होता है।
def decorator_a(func):
def wrapper(*args, **kwargs):
print('A: before')
result = func(*args, **kwargs)
print('A: after')
return result
return wrapper
def decorator_b(func):
def wrapper(*args, **kwargs):
print('B: before')
result = func(*args, **kwargs)
print('B: after')
return result
return wrapper
@decorator_a
@decorator_b
def greet():
print('Hello!')
greet()
# A: before
# B: before
# Hello!
# B: after
# A: after
# बराबर है:
def greet2():
print('Hello!')
greet2 = decorator_a(decorator_b(greet2))
# Practical example - auth + logging
def require_auth(func):
def wrapper(*args, **kwargs):
print('Authentication check...')
return func(*args, **kwargs)
return wrapper
def log_call(func):
def wrapper(*args, **kwargs):
print(f'Calling {func.__name__}')
return func(*args, **kwargs)
return wrapper
@require_auth
@log_call
def delete_user(user_id):
print(f'User {user_id} delete हो रहा है')
delete_user(5)Was this answer clear?