Range Over Channels in Python

Our first example demonstrates how to iterate over values received from a channel. In Python, we’ll use a queue from the queue module to simulate this behavior.

import queue

def main():
    # We'll iterate over 2 values in the queue
    q = queue.Queue(maxsize=2)
    q.put("one")
    q.put("two")

    # This loop iterates over each element as it's
    # received from the queue. Because we've added
    # only two elements, the iteration terminates
    # after receiving the 2 elements.
    while not q.empty():
        elem = q.get()
        print(elem)

if __name__ == "__main__":
    main()

To run the program:

$ python range_over_channels.py
one
two

This example shows how to iterate over elements in a queue, which is similar to ranging over a channel in other languages. In Python, we use a while loop to check if the queue is empty, and get() to retrieve elements.

Note that unlike some other languages, Python’s queue doesn’t have a built-in “close” method. The iteration naturally terminates when all elements have been retrieved from the queue.

This approach demonstrates how to process a series of elements in a queue-like structure, which can be useful in scenarios involving producer-consumer patterns or when dealing with asynchronous data streams.