Tuesday, August 26, 2025

🐍PRACTICE EXERCISES ON DECORATORS

Practice Exercises on Decorators

It’s time to put your knowledge to test! Try these exercises to master decorators in Python.

1) Logging Function Calls

Write a decorator called log_calls that prints the function name and its arguments whenever it is called.


# Example:
@log_calls
def greet(name, age):
    print(f"Hello {name}, you are {age} years old!")

greet("Alice", 25)
# Expected Output:
# Function greet called with arguments ('Alice', 25)
# Hello Alice, you are 25 years old!

2) Measure Execution Time

Create a decorator timer that measures and prints how long a function takes to execute.


# Example:
@timer
def slow_function():
    import time
    time.sleep(2)
    print("Finished!")

slow_function()
# Expected Output:
# Finished!
# slow_function took ~2.0 seconds

3) Restrict Access

Build a decorator require_admin that allows a function to execute only if the user argument is "admin".


# Example:
@require_admin
def delete_user(user, username):
    print(f"User {username} deleted by {user}")

delete_user("guest", "Alice")   # Access denied
delete_user("admin", "Bob")     # Works

4) Cache Function Results

Implement a decorator cache_results to store results of a function and return cached values if the same arguments are passed again.


# Example:
@cache_results
def multiply(a, b):
    print("Calculating...")
    return a * b

print(multiply(2, 5))  # Calculates
print(multiply(2, 5))  # Fetches from cache

Tips

  • Always handle *args and **kwargs in wrappers.
  • Use functools.wraps to preserve function metadata.
  • Start with simple decorators and gradually combine multiple decorators.
  • Test each decorator separately before applying it to complex functions.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??