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.
x
20
1
def filipino_greeting_decorator(func):
2
def wrapper():
3
print("Mabuhay! Starting the function...")
4
func()
5
print("Salamat! Function completed.")
6
return wrapper
7
8
9
def celebrate_festival():
10
print("Nagpupugay sa Pasko at mga Pista!")
11
12
celebrate_festival()
13
14
"""
15
Expected Output:
16
17
Mabuhay! Starting the function...
18
Nagpupugay sa Pasko at mga Pista!
19
Salamat! Function completed.
20
"""
Decorator with Arguments using enumerate
Enhance a function that schedules festival events by logging each event with its number.
1
23
1
def event_logger_decorator(func):
2
def wrapper(festival, events):
3
print(f"Scheduling events for {festival}:")
4
func(festival, events)
5
return wrapper
6
7
8
def schedule_events(festival, events):
9
for idx, event in enumerate(events, start=1):
10
print(f"{idx}. {event}")
11
12
festival_events = ["Street Dancing", "Parade", "Cultural Show", "Fireworks"]
13
schedule_events("Sinulog", festival_events)
14
15
"""
16
Expected Output:
17
18
Scheduling events for Sinulog:
19
1. Street Dancing
20
2. Parade
21
3. Cultural Show
22
4. Fireworks
23
"""