8) Abstract Data Structures Lesson

Extend the Python Queue

3 min to complete · By Martin Breuss

Now, let's use a decorator to add some additional functionality to your queue's .dequeue() method. You'll create a decorator called @dequeue_with_logging that logs the item you pop as well as the current size of the queue before and after the operation:

def dequeue_with_logging(func):
    def wrapper(self):
        print(f"Getting item... Current queue size: {self.length}")
        item = func(self)
        print(f"Got item: {item}. Updated queue size: {self.length}")
        return item
    return wrapper

To use this decorator, you'll need to update the Queue class to include @dequeue_with_logging before the .dequeue() method definition:

class Queue:
    # ...
    
    @dequeue_with_logging
    def dequeue(self):
        # ...

How to Use the Decorator

To use the @dequeue_with_logging decorator, you'll need to create a Queue object and add some items to it using the .enqueue(). Then, you can call .dequeue() on the queue object just like you did before to remove and return the first item in the queue. Additionally, the @dequeue_with_logging decorator will now log the item you pop and the current size of the queue before and after the pop operation and print them to your terminal.

Run the code to create your morning_tasks another time and see how the output improved with the @dequeue_with_logging decorator:

morning_tasks = Queue()
morning_tasks.enqueue("get dressed")
morning_tasks.enqueue("eat breakfast")
morning_tasks.enqueue("go to work")

# Dequeue and see the decorated logging output
task = morning_tasks.dequeue() 
# OUTPUT:
# Getting item... Current queue size: 3
# Got item: get dressed. Updated queue size: 2

print(f"Todo: {task}")  # Todo: get dressed

When you call .dequeue() after the code change, then the output shows that the item you popped is "get dressed" just like it did before. However, with the decorated method, the output also logs that the initial size of the queue is 3 before the pop operation and 2 afterward.

Colorful illustration of a light bulb

Addition Resources

Summary: Extend the Python Queue

  • Decorators can be used with a Python Queue
  • The provided decorator logs the new item and the size of the Queue