Python Decorators

1) Simple Decorator (Before)

Write a decorator my_decorator that prints:

Before function

before calling the wrapped function.


2) Simple Decorator (After)

Modify the decorator so it prints:

After function

after calling the wrapped function.


3) Decorator That Prints Function Name

Write a decorator that prints the name of the function being called.


4) Decorator to Log Arguments

Write a decorator that prints the arguments passed to the function.

Example:

Calling greet with ('Alice',)

5) Decorator to Time Execution

Create a decorator that prints how long the wrapped function runs.


6) Decorator That Modifies Return

Write a decorator that multiplies the return value of a function by 2.


7) Using Decorator with No Arguments

Apply a decorator to a simple function say_hello() that just prints "Hi!".


8) Decorator for Greeting

Write a decorator that adds “Good Morning” before the function output.

Example:


9) Multiple Decorators

Apply two decorators to the same function (e.g., one prints before, one prints after).


10) Decorator With Parameter

Create a decorator that takes a parameter (like a prefix string) and uses it when printing.

Example:


11) Decorator for Even/Odd Output

Write a decorator that checks if the returned number from a function is even or odd and prints that.


12) Decorator With Function Metadata

Use functools.wraps in your decorator so the wrapped function keeps its original __name__.


13) Decorator to Prevent Execution

Write a decorator that prevents the function from running when a global switch disabled = True is set.


14) Decorator That Repeats Function

Write a decorator that runs the wrapped function 3 times.


15) Decorator That Modifies Input

Create a decorator that automatically converts all string arguments to uppercase before calling the function.

Example:


16) Decorator to Catch Exceptions

Write a decorator that catches exceptions and prints:

instead of crashing.


17) Decorator That Caches Results

Write a simple caching decorator that stores and reuses return values by input args.


18) Decorator With Conditional Logic

Write a decorator that skips running the function if a passed-in flag is False.


19) Class Decorator

Create a decorator (as a class with __call__) that prints "Decorated" before function runs.


20) Decorator Logger to File

Write a decorator that logs the function name and timestamp to a file (log.txt) each time the function is called.


🧠 Concepts Covered

Concept
Key Idea

Basic decorator syntax

@my_decorator

Decorating with parameters

@decorator(arg)

Nested decorators

stacking @

Modifying behavior

before/after/wrap

preserving metadata

functools.wraps

exception handling & caching

advanced patterns


🧩 Starter Template

Here’s a minimal decorator you can reuse:

Usage:


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated