What are Python Decorators?
Decorators are special functions in Python that modify or enhance other functions without changing their actual code. They wrap another function to extend its behavior in a clean and readable way.
Why Use Decorators?
- Code Reusability: Apply the same enhancement to multiple functions without repeating code.
- Separation of Concerns: Keep core functionality separate from auxiliary features like logging or access control.
- Improved Readability: Make code more organized and easier to understand.
How to Use Decorators?
Creating a Simple Decorator
Let’s create a decorator that adds Filipino greetings before and after a function executes.
def filipino_greeting_decorator(func): def wrapper(): print("Mabuhay! Starting the function...") func() print("Salamat! Function completed.") return wrapper @filipino_greeting_decorator def celebrate_festival(): print("Nagpupugay sa Pasko at mga Pista!") celebrate_festival() """ Expected Output: Mabuhay! Starting the function... Nagpupugay sa Pasko at mga Pista! Salamat! Function completed. """
Decorator with Arguments using enumerate
Enhance a function that schedules festival events by logging each event with its number.
def event_logger_decorator(func): def wrapper(festival, events): print(f"Scheduling events for {festival}:") func(festival, events) return wrapper @event_logger_decorator def schedule_events(festival, events): for idx, event in enumerate(events, start=1): print(f"{idx}. {event}") festival_events = ["Street Dancing", "Parade", "Cultural Show", "Fireworks"] schedule_events("Sinulog", festival_events) """ Expected Output: Scheduling events for Sinulog: 1. Street Dancing 2. Parade 3. Cultural Show 4. Fireworks """