Search code examples
pythondeque

View into a Deque


I have a fixed length deque which receives pushed items on the left.

Periodically I wish to copy all of the values, without affecting the elements in the deque. I'm using the more_itertools "spy" function as follows:

from collections import deque
from more_itertools import spy

d = deque(maxlen=3)
d.appendleft(1)
d.appendleft(2)
d.appendleft(3)

# Setup
D = spy(d, n=3)
print(D[0])  # >>>[3, 2, 1]

# Now add another item and retrieve the snapshot again
d.appendleft(4)
print(D[0])  # >>>[3, 2, 1]  Same! I want: [4, 3, 2]

Solution

  • The spy function from more_itertools doesn't do what what you seem to expect it to do. It makes a one-time copy of the first n values from the argument, and returns it in a tuple with an iterator that still behaves like the argument (even if the argument was an iterator, not a sequence that can be repeatedly iterated upon).

    For your use, you should just copy the deque values each time you want them. Instead of print(D[0]), just do print(list(d)) (or just print(d) if you're not picky about the formatting).