Python Function decorators
1. What is a Function Decorator?
A function decorator is a function that adds extra work to another function.
In simple words:
👉 A decorator wraps a function
👉 It runs before or after the function
👉 The original function code does not change
2. Real-Life Example
Think of a mobile phone cover 📱
-
Phone = function
-
Cover = decorator
The cover adds protection without changing the phone.
3. Why Use Function Decorators?
We use decorators to:
✔ Add logging
✔ Add security checks
✔ Measure time
✔ Reuse code again and again
4. Function Without Decorator
Example
5. Create a Simple Function Decorator
Step 1: Create Decorator Function
Step 2: Apply Decorator
Output:
6. How @decorator Works?
This:
7. Function Decorator with Arguments
Example
8. Decorator with Multiple Arguments
Example
9. Real-Life Example: Login Check
Example
10. Using functools.wraps (Good Practice)
This keeps function name and details safe.
Example
11. Common Beginner Mistakes
❌ Forgetting to Call Function
✔ Correct:
❌ Forgetting to Return Wrapper
❌ Wrong.
12. Simple Practice Examples
Example 1: Time Message Decorator
Example 2: Math Decorator
Example 3: Decorator Without @
13. Summary (Python Function Decorators)
✔ Decorators modify functions
✔ Use @decorator_name
✔ Wrapper function is important
✔ Supports arguments
✔ Very powerful Python feature
📘 Perfect for Beginner & Advanced eBook
This chapter is ideal for:
-
Python learners
-
Interview preparation
-
Real-world projects
-
Writing clean code
If you want next, I can write:
-
Class Decorators
-
Decorator Chaining
-
Advanced Decorators
-
Real Python Projects
Just tell me 😊
