Skip to main content

Decorators & Generators 🚀

Python Decorators & Generators is a core Python concept covering master advanced Python tools. Learn how to wrap functions with Decorators and process huge data with Generators using the Gift Wrapper scenario. This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.

Mentor's Note: Decorators and Generators are what make Python feel "Magic." They allow you to add features to code without changing it, and process millions of lines of data without crashing your RAM! 💡


🌟 The Scenario: The Gift Wrapper 🎁

Imagine you have a shop that sells plain boxes.

  • The Decorator (The Wrapper): A customer wants a box, but they want it wrapped in Shiny Paper ✨ and a Ribbon 🎀. You don't build a new box; you just "Wrap" the existing one. 📦
  • The Generator (The Candy Machine): A customer wants 1,000 candies. Instead of handing them a giant heavy bag (A List), you give them a Candy Machine 🍬. They turn the handle, and get one candy at a time whenever they are ready.
  • The Result: You save space in your shop and make the customer happy! ✅

📖 Concept Explanation

1. Python Decorators

A decorator is a function that takes another function and extends its behavior without explicitly modifying it.

  • Syntax: @decorator_name placed above a function.

2. Python Generators

Generators are special functions that return an Iterator object. They use the yield keyword instead of return.

  • Logic: "I'm not finished, just pausing here. Call me again for the next item!" ⏸️

🎨 Visual Logic: The Generator Flow


💻 Implementation: The Advanced Lab

# 🛒 Scenario: Adding a 'Log' to every action
# 🚀 Action: Creating a logger decorator

def log_action(func):
def wrapper():
print("LOG: Action is starting... 🕒")
func()
print("LOG: Action finished. ✅")
return wrapper

@log_action
def say_hello():
print("Hello, VishnuDigital!")

say_hello()

📊 Sample Dry Run (Generators)

Function: yield 1; yield 2;

TurnStatusActionOutput
1StartedRun until 1st yield1
2PausedResume and run until 2nd yield2
3FinishedNo more yields foundStopIteration 🏁

📉 Technical Analysis

  • Memory Efficiency: A list of 1 million numbers takes ~40MB of RAM. A generator for 1 million numbers takes ~100 bytes. 🤯
  • Lazy Evaluation: Generators only calculate the next value when you actually ask for it.

🎯 Practice Lab 🧪

Task: The Timer Decorator

Task: Create a decorator @timer that prints how many seconds a function takes to run. Hint: Use import time and calculate end_time - start_time. 💡


💡 Interview Tip 👔

"Interviewers love asking: 'What is the difference between yield and return?' Answer: return destroys the function's local state and exits. yield pauses the function, saves its state, and can be resumed later!"


💡 Pro Tip: "Writing clean code is what you do when you care about the people who will read it—including yourself in six months!" - Anonymous



← Back: Algorithms | Next: Regex & Multiprocessing →

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir