blob: 2ca508d7e82839380ed38999f0a8e9de84b60379 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001from collections import deque
2import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support, seq_tests
Antoine Pitrou7ddda782009-01-01 15:35:33 +00004import gc
5import weakref
Raymond Hettinger756b3f32004-01-29 06:37:52 +00006import copy
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00007import pickle
Guido van Rossum34d19282007-08-09 01:03:29 +00008from io import StringIO
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00009import random
Jesus Cea16e2fca2012-08-03 14:49:42 +020010import struct
Raymond Hettinger756b3f32004-01-29 06:37:52 +000011
12BIG = 100000
13
Raymond Hettingera435c532004-07-09 04:10:20 +000014def fail():
15 raise SyntaxError
16 yield 1
17
Raymond Hettinger4aec61e2005-03-18 21:20:23 +000018class BadCmp:
19 def __eq__(self, other):
20 raise RuntimeError
21
22class MutateCmp:
Raymond Hettingerd73202c2005-03-19 00:00:51 +000023 def __init__(self, deque, result):
Raymond Hettinger4aec61e2005-03-18 21:20:23 +000024 self.deque = deque
Raymond Hettingerd73202c2005-03-19 00:00:51 +000025 self.result = result
Raymond Hettinger4aec61e2005-03-18 21:20:23 +000026 def __eq__(self, other):
27 self.deque.clear()
Raymond Hettingerd73202c2005-03-19 00:00:51 +000028 return self.result
Raymond Hettinger4aec61e2005-03-18 21:20:23 +000029
Raymond Hettinger756b3f32004-01-29 06:37:52 +000030class TestBasic(unittest.TestCase):
31
32 def test_basics(self):
Christian Heimes38053212007-12-14 01:24:44 +000033 d = deque(range(-5125, -5000))
34 d.__init__(range(200))
Guido van Rossum805365e2007-05-07 22:24:25 +000035 for i in range(200, 400):
Raymond Hettinger756b3f32004-01-29 06:37:52 +000036 d.append(i)
Guido van Rossum805365e2007-05-07 22:24:25 +000037 for i in reversed(range(-200, 0)):
Raymond Hettinger756b3f32004-01-29 06:37:52 +000038 d.appendleft(i)
Guido van Rossum805365e2007-05-07 22:24:25 +000039 self.assertEqual(list(d), list(range(-200, 400)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +000040 self.assertEqual(len(d), 600)
41
Guido van Rossum805365e2007-05-07 22:24:25 +000042 left = [d.popleft() for i in range(250)]
43 self.assertEqual(left, list(range(-200, 50)))
44 self.assertEqual(list(d), list(range(50, 400)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +000045
Guido van Rossum805365e2007-05-07 22:24:25 +000046 right = [d.pop() for i in range(250)]
Raymond Hettinger756b3f32004-01-29 06:37:52 +000047 right.reverse()
Guido van Rossum805365e2007-05-07 22:24:25 +000048 self.assertEqual(right, list(range(150, 400)))
49 self.assertEqual(list(d), list(range(50, 150)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +000050
Guido van Rossum8ce8a782007-11-01 19:42:39 +000051 def test_maxlen(self):
52 self.assertRaises(ValueError, deque, 'abc', -1)
53 self.assertRaises(ValueError, deque, 'abc', -2)
Raymond Hettinger060c7f62009-03-10 09:36:07 +000054 it = iter(range(10))
55 d = deque(it, maxlen=3)
56 self.assertEqual(list(it), [])
Guido van Rossum8ce8a782007-11-01 19:42:39 +000057 self.assertEqual(repr(d), 'deque([7, 8, 9], maxlen=3)')
58 self.assertEqual(list(d), [7, 8, 9])
59 self.assertEqual(d, deque(range(10), 3))
60 d.append(10)
61 self.assertEqual(list(d), [8, 9, 10])
62 d.appendleft(7)
63 self.assertEqual(list(d), [7, 8, 9])
64 d.extend([10, 11])
65 self.assertEqual(list(d), [9, 10, 11])
66 d.extendleft([8, 7])
67 self.assertEqual(list(d), [7, 8, 9])
68 d = deque(range(200), maxlen=10)
69 d.append(d)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000070 support.unlink(support.TESTFN)
71 fo = open(support.TESTFN, "w")
Christian Heimescc47b052008-03-25 14:56:36 +000072 try:
73 fo.write(str(d))
74 fo.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +000075 fo = open(support.TESTFN, "r")
Christian Heimescc47b052008-03-25 14:56:36 +000076 self.assertEqual(fo.read(), repr(d))
77 finally:
78 fo.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +000079 support.unlink(support.TESTFN)
Christian Heimescc47b052008-03-25 14:56:36 +000080
Guido van Rossum8ce8a782007-11-01 19:42:39 +000081 d = deque(range(10), maxlen=None)
82 self.assertEqual(repr(d), 'deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])')
Benjamin Petersonee8712c2008-05-20 21:35:26 +000083 fo = open(support.TESTFN, "w")
Christian Heimescc47b052008-03-25 14:56:36 +000084 try:
85 fo.write(str(d))
86 fo.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +000087 fo = open(support.TESTFN, "r")
Christian Heimescc47b052008-03-25 14:56:36 +000088 self.assertEqual(fo.read(), repr(d))
89 finally:
90 fo.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +000091 support.unlink(support.TESTFN)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000092
Raymond Hettinger060c7f62009-03-10 09:36:07 +000093 def test_maxlen_zero(self):
94 it = iter(range(100))
95 deque(it, maxlen=0)
96 self.assertEqual(list(it), [])
97
98 it = iter(range(100))
99 d = deque(maxlen=0)
100 d.extend(it)
101 self.assertEqual(list(it), [])
102
103 it = iter(range(100))
104 d = deque(maxlen=0)
105 d.extendleft(it)
106 self.assertEqual(list(it), [])
107
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000108 def test_maxlen_attribute(self):
109 self.assertEqual(deque().maxlen, None)
110 self.assertEqual(deque('abc').maxlen, None)
111 self.assertEqual(deque('abc', maxlen=4).maxlen, 4)
112 self.assertEqual(deque('abc', maxlen=2).maxlen, 2)
113 self.assertEqual(deque('abc', maxlen=0).maxlen, 0)
114 with self.assertRaises(AttributeError):
115 d = deque('abc')
116 d.maxlen = 10
117
Raymond Hettinger44459de2010-04-03 23:20:46 +0000118 def test_count(self):
119 for s in ('', 'abracadabra', 'simsalabim'*500+'abc'):
120 s = list(s)
121 d = deque(s)
122 for letter in 'abcdefghijklmnopqrstuvwxyz':
123 self.assertEqual(s.count(letter), d.count(letter), (s, d, letter))
124 self.assertRaises(TypeError, d.count) # too few args
125 self.assertRaises(TypeError, d.count, 1, 2) # too many args
126 class BadCompare:
127 def __eq__(self, other):
128 raise ArithmeticError
129 d = deque([1, 2, BadCompare(), 3])
130 self.assertRaises(ArithmeticError, d.count, 2)
131 d = deque([1, 2, 3])
132 self.assertRaises(ArithmeticError, d.count, BadCompare())
133 class MutatingCompare:
134 def __eq__(self, other):
135 self.d.pop()
136 return True
137 m = MutatingCompare()
138 d = deque([1, 2, 3, m, 4, 5])
139 m.d = d
140 self.assertRaises(RuntimeError, d.count, 3)
141
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000142 # test issue11004
143 # block advance failed after rotation aligned elements on right side of block
144 d = deque([None]*16)
145 for i in range(len(d)):
146 d.rotate(-1)
147 d.rotate(1)
148 self.assertEqual(d.count(1), 0)
149 self.assertEqual(d.count(None), 16)
150
Raymond Hettinger738ec902004-02-29 02:15:56 +0000151 def test_comparisons(self):
152 d = deque('xabc'); d.popleft()
153 for e in [d, deque('abc'), deque('ab'), deque(), list(d)]:
154 self.assertEqual(d==e, type(d)==type(e) and list(d)==list(e))
155 self.assertEqual(d!=e, not(type(d)==type(e) and list(d)==list(e)))
156
157 args = map(deque, ('', 'a', 'b', 'ab', 'ba', 'abc', 'xba', 'xabc', 'cba'))
158 for x in args:
159 for y in args:
160 self.assertEqual(x == y, list(x) == list(y), (x,y))
161 self.assertEqual(x != y, list(x) != list(y), (x,y))
162 self.assertEqual(x < y, list(x) < list(y), (x,y))
163 self.assertEqual(x <= y, list(x) <= list(y), (x,y))
164 self.assertEqual(x > y, list(x) > list(y), (x,y))
165 self.assertEqual(x >= y, list(x) >= list(y), (x,y))
Raymond Hettinger738ec902004-02-29 02:15:56 +0000166
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700167 def test_contains(self):
168 n = 200
169
170 d = deque(range(n))
171 for i in range(n):
172 self.assertTrue(i in d)
173 self.assertTrue((n+1) not in d)
174
175 # Test detection of mutation during iteration
176 d = deque(range(n))
177 d[n//2] = MutateCmp(d, False)
178 with self.assertRaises(RuntimeError):
179 n in d
180
181 # Test detection of comparison exceptions
182 d = deque(range(n))
183 d[n//2] = BadCmp()
184 with self.assertRaises(RuntimeError):
185 n in d
186
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000187 def test_extend(self):
188 d = deque('a')
189 self.assertRaises(TypeError, d.extend, 1)
190 d.extend('bcd')
191 self.assertEqual(list(d), list('abcd'))
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000192 d.extend(d)
193 self.assertEqual(list(d), list('abcdabcd'))
194
Raymond Hettinger41290a62015-03-31 08:12:23 -0700195 def test_add(self):
196 d = deque()
197 e = deque('abc')
198 f = deque('def')
199 self.assertEqual(d + d, deque())
200 self.assertEqual(e + f, deque('abcdef'))
201 self.assertEqual(e + e, deque('abcabc'))
202 self.assertEqual(e + d, deque('abc'))
203 self.assertEqual(d + e, deque('abc'))
204 self.assertIsNot(d + d, deque())
205 self.assertIsNot(e + d, deque('abc'))
206 self.assertIsNot(d + e, deque('abc'))
207
208 g = deque('abcdef', maxlen=4)
209 h = deque('gh')
210 self.assertEqual(g + h, deque('efgh'))
211
212 with self.assertRaises(TypeError):
213 deque('abc') + 'def'
214
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000215 def test_iadd(self):
216 d = deque('a')
217 d += 'bcd'
218 self.assertEqual(list(d), list('abcd'))
219 d += d
220 self.assertEqual(list(d), list('abcdabcd'))
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000221
222 def test_extendleft(self):
223 d = deque('a')
224 self.assertRaises(TypeError, d.extendleft, 1)
225 d.extendleft('bcd')
226 self.assertEqual(list(d), list(reversed('abcd')))
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000227 d.extendleft(d)
228 self.assertEqual(list(d), list('abcddcba'))
Raymond Hettingera435c532004-07-09 04:10:20 +0000229 d = deque()
230 d.extendleft(range(1000))
231 self.assertEqual(list(d), list(reversed(range(1000))))
232 self.assertRaises(SyntaxError, d.extendleft, fail())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000233
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000234 def test_getitem(self):
235 n = 200
Guido van Rossum805365e2007-05-07 22:24:25 +0000236 d = deque(range(n))
237 l = list(range(n))
238 for i in range(n):
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000239 d.popleft()
240 l.pop(0)
241 if random.random() < 0.5:
242 d.append(i)
243 l.append(i)
Guido van Rossum805365e2007-05-07 22:24:25 +0000244 for j in range(1-len(l), len(l)):
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000245 assert d[j] == l[j]
246
Raymond Hettinger738ec902004-02-29 02:15:56 +0000247 d = deque('superman')
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000248 self.assertEqual(d[0], 's')
249 self.assertEqual(d[-1], 'n')
Raymond Hettinger738ec902004-02-29 02:15:56 +0000250 d = deque()
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000251 self.assertRaises(IndexError, d.__getitem__, 0)
252 self.assertRaises(IndexError, d.__getitem__, -1)
253
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700254 def test_index(self):
255 for n in 1, 2, 30, 40, 200:
256
257 d = deque(range(n))
258 for i in range(n):
259 self.assertEqual(d.index(i), i)
260
261 with self.assertRaises(ValueError):
262 d.index(n+1)
263
264 # Test detection of mutation during iteration
265 d = deque(range(n))
266 d[n//2] = MutateCmp(d, False)
267 with self.assertRaises(RuntimeError):
268 d.index(n)
269
270 # Test detection of comparison exceptions
271 d = deque(range(n))
272 d[n//2] = BadCmp()
273 with self.assertRaises(RuntimeError):
274 d.index(n)
275
276 # Test start and stop arguments behavior matches list.index()
277 elements = 'ABCDEFGHI'
278 nonelement = 'Z'
279 d = deque(elements * 2)
280 s = list(elements * 2)
281 for start in range(-5 - len(s)*2, 5 + len(s) * 2):
282 for stop in range(-5 - len(s)*2, 5 + len(s) * 2):
283 for element in elements + 'Z':
284 try:
285 target = s.index(element, start, stop)
286 except ValueError:
287 with self.assertRaises(ValueError):
288 d.index(element, start, stop)
289 else:
290 self.assertEqual(d.index(element, start, stop), target)
291
Brett Cannondf6b5442015-09-03 10:15:03 -0700292 def test_insert_bug_24913(self):
293 d = deque('A' * 3)
294 with self.assertRaises(ValueError):
295 i = d.index("Hello world", 0, 4)
296
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700297 def test_insert(self):
298 # Test to make sure insert behaves like lists
299 elements = 'ABCDEFGHI'
300 for i in range(-5 - len(elements)*2, 5 + len(elements) * 2):
301 d = deque('ABCDEFGHI')
302 s = list('ABCDEFGHI')
303 d.insert(i, 'Z')
304 s.insert(i, 'Z')
305 self.assertEqual(list(d), s)
306
Raymond Hettingerb00da572016-02-01 21:19:22 -0800307 def test_insert_bug_26194(self):
Raymond Hettinger37434322016-01-26 21:44:16 -0800308 data = 'ABC'
Raymond Hettingerb00da572016-02-01 21:19:22 -0800309 d = deque(data, maxlen=len(data))
310 with self.assertRaises(IndexError):
311 d.insert(2, None)
312
313 elements = 'ABCDEFGHI'
314 for i in range(-len(elements), len(elements)):
315 d = deque(elements, maxlen=len(elements)+1)
316 d.insert(i, 'Z')
317 if i >= 0:
318 self.assertEqual(d[i], 'Z')
Raymond Hettinger37434322016-01-26 21:44:16 -0800319 else:
Raymond Hettingerb00da572016-02-01 21:19:22 -0800320 self.assertEqual(d[i-1], 'Z')
Raymond Hettinger37434322016-01-26 21:44:16 -0800321
Raymond Hettinger41290a62015-03-31 08:12:23 -0700322 def test_imul(self):
323 for n in (-10, -1, 0, 1, 2, 10, 1000):
324 d = deque()
325 d *= n
326 self.assertEqual(d, deque())
327 self.assertIsNone(d.maxlen)
328
329 for n in (-10, -1, 0, 1, 2, 10, 1000):
330 d = deque('a')
331 d *= n
332 self.assertEqual(d, deque('a' * n))
333 self.assertIsNone(d.maxlen)
334
335 for n in (-10, -1, 0, 1, 2, 10, 499, 500, 501, 1000):
336 d = deque('a', 500)
337 d *= n
338 self.assertEqual(d, deque('a' * min(n, 500)))
339 self.assertEqual(d.maxlen, 500)
340
341 for n in (-10, -1, 0, 1, 2, 10, 1000):
342 d = deque('abcdef')
343 d *= n
344 self.assertEqual(d, deque('abcdef' * n))
345 self.assertIsNone(d.maxlen)
346
347 for n in (-10, -1, 0, 1, 2, 10, 499, 500, 501, 1000):
348 d = deque('abcdef', 500)
349 d *= n
350 self.assertEqual(d, deque(('abcdef' * n)[-500:]))
351 self.assertEqual(d.maxlen, 500)
352
353 def test_mul(self):
354 d = deque('abc')
355 self.assertEqual(d * -5, deque())
356 self.assertEqual(d * 0, deque())
357 self.assertEqual(d * 1, deque('abc'))
358 self.assertEqual(d * 2, deque('abcabc'))
359 self.assertEqual(d * 3, deque('abcabcabc'))
360 self.assertIsNot(d * 1, d)
361
362 self.assertEqual(deque() * 0, deque())
363 self.assertEqual(deque() * 1, deque())
364 self.assertEqual(deque() * 5, deque())
365
366 self.assertEqual(-5 * d, deque())
367 self.assertEqual(0 * d, deque())
368 self.assertEqual(1 * d, deque('abc'))
369 self.assertEqual(2 * d, deque('abcabc'))
370 self.assertEqual(3 * d, deque('abcabcabc'))
371
372 d = deque('abc', maxlen=5)
373 self.assertEqual(d * -5, deque())
374 self.assertEqual(d * 0, deque())
375 self.assertEqual(d * 1, deque('abc'))
376 self.assertEqual(d * 2, deque('bcabc'))
377 self.assertEqual(d * 30, deque('bcabc'))
378
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000379 def test_setitem(self):
380 n = 200
Guido van Rossum805365e2007-05-07 22:24:25 +0000381 d = deque(range(n))
382 for i in range(n):
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000383 d[i] = 10 * i
Guido van Rossum805365e2007-05-07 22:24:25 +0000384 self.assertEqual(list(d), [10*i for i in range(n)])
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000385 l = list(d)
Guido van Rossum805365e2007-05-07 22:24:25 +0000386 for i in range(1-n, 0, -1):
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000387 d[i] = 7*i
388 l[i] = 7*i
389 self.assertEqual(list(d), l)
Raymond Hettinger738ec902004-02-29 02:15:56 +0000390
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000391 def test_delitem(self):
392 n = 500 # O(n**2) test, don't make this too big
Guido van Rossum805365e2007-05-07 22:24:25 +0000393 d = deque(range(n))
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000394 self.assertRaises(IndexError, d.__delitem__, -n-1)
395 self.assertRaises(IndexError, d.__delitem__, n)
Guido van Rossum805365e2007-05-07 22:24:25 +0000396 for i in range(n):
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000397 self.assertEqual(len(d), n-i)
398 j = random.randrange(-len(d), len(d))
399 val = d[j]
Benjamin Peterson577473f2010-01-19 00:09:57 +0000400 self.assertIn(val, d)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000401 del d[j]
Benjamin Peterson577473f2010-01-19 00:09:57 +0000402 self.assertNotIn(val, d)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000403 self.assertEqual(len(d), 0)
404
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000405 def test_reverse(self):
406 n = 500 # O(n**2) test, don't make this too big
407 data = [random.random() for i in range(n)]
408 for i in range(n):
409 d = deque(data[:i])
410 r = d.reverse()
411 self.assertEqual(list(d), list(reversed(data[:i])))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000412 self.assertIs(r, None)
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000413 d.reverse()
414 self.assertEqual(list(d), data[:i])
415 self.assertRaises(TypeError, d.reverse, 1) # Arity is zero
416
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000417 def test_rotate(self):
Raymond Hettingeree33b272004-02-08 04:05:26 +0000418 s = tuple('abcde')
419 n = len(s)
420
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000421 d = deque(s)
Raymond Hettingeree33b272004-02-08 04:05:26 +0000422 d.rotate(1) # verify rot(1)
423 self.assertEqual(''.join(d), 'eabcd')
424
425 d = deque(s)
426 d.rotate(-1) # verify rot(-1)
427 self.assertEqual(''.join(d), 'bcdea')
428 d.rotate() # check default to 1
429 self.assertEqual(tuple(d), s)
430
Guido van Rossum805365e2007-05-07 22:24:25 +0000431 for i in range(n*3):
Raymond Hettingeree33b272004-02-08 04:05:26 +0000432 d = deque(s)
433 e = deque(d)
434 d.rotate(i) # check vs. rot(1) n times
Guido van Rossum805365e2007-05-07 22:24:25 +0000435 for j in range(i):
Raymond Hettingeree33b272004-02-08 04:05:26 +0000436 e.rotate(1)
437 self.assertEqual(tuple(d), tuple(e))
438 d.rotate(-i) # check that it works in reverse
439 self.assertEqual(tuple(d), s)
440 e.rotate(n-i) # check that it wraps forward
441 self.assertEqual(tuple(e), s)
442
Guido van Rossum805365e2007-05-07 22:24:25 +0000443 for i in range(n*3):
Raymond Hettingeree33b272004-02-08 04:05:26 +0000444 d = deque(s)
445 e = deque(d)
446 d.rotate(-i)
Guido van Rossum805365e2007-05-07 22:24:25 +0000447 for j in range(i):
Raymond Hettingeree33b272004-02-08 04:05:26 +0000448 e.rotate(-1) # check vs. rot(-1) n times
449 self.assertEqual(tuple(d), tuple(e))
450 d.rotate(i) # check that it works in reverse
451 self.assertEqual(tuple(d), s)
452 e.rotate(i-n) # check that it wraps backaround
453 self.assertEqual(tuple(e), s)
454
455 d = deque(s)
456 e = deque(s)
457 e.rotate(BIG+17) # verify on long series of rotates
458 dr = d.rotate
Guido van Rossum805365e2007-05-07 22:24:25 +0000459 for i in range(BIG+17):
Raymond Hettingeree33b272004-02-08 04:05:26 +0000460 dr()
461 self.assertEqual(tuple(d), tuple(e))
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000462
Raymond Hettingera435c532004-07-09 04:10:20 +0000463 self.assertRaises(TypeError, d.rotate, 'x') # Wrong arg type
464 self.assertRaises(TypeError, d.rotate, 1, 10) # Too many args
465
466 d = deque()
467 d.rotate() # rotate an empty deque
468 self.assertEqual(d, deque())
469
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000470 def test_len(self):
471 d = deque('ab')
472 self.assertEqual(len(d), 2)
473 d.popleft()
474 self.assertEqual(len(d), 1)
475 d.pop()
476 self.assertEqual(len(d), 0)
Raymond Hettinger738ec902004-02-29 02:15:56 +0000477 self.assertRaises(IndexError, d.pop)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000478 self.assertEqual(len(d), 0)
479 d.append('c')
480 self.assertEqual(len(d), 1)
481 d.appendleft('d')
482 self.assertEqual(len(d), 2)
483 d.clear()
484 self.assertEqual(len(d), 0)
485
486 def test_underflow(self):
487 d = deque()
Raymond Hettinger738ec902004-02-29 02:15:56 +0000488 self.assertRaises(IndexError, d.pop)
489 self.assertRaises(IndexError, d.popleft)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000490
491 def test_clear(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000492 d = deque(range(100))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000493 self.assertEqual(len(d), 100)
494 d.clear()
495 self.assertEqual(len(d), 0)
496 self.assertEqual(list(d), [])
Raymond Hettingera435c532004-07-09 04:10:20 +0000497 d.clear() # clear an emtpy deque
498 self.assertEqual(list(d), [])
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000499
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000500 def test_remove(self):
501 d = deque('abcdefghcij')
502 d.remove('c')
503 self.assertEqual(d, deque('abdefghcij'))
504 d.remove('c')
505 self.assertEqual(d, deque('abdefghij'))
506 self.assertRaises(ValueError, d.remove, 'c')
507 self.assertEqual(d, deque('abdefghij'))
508
Walter Dörwaldc448a912005-03-22 11:22:38 +0000509 # Handle comparison errors
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000510 d = deque(['a', 'b', BadCmp(), 'c'])
511 e = deque(d)
512 self.assertRaises(RuntimeError, d.remove, 'c')
513 for x, y in zip(d, e):
514 # verify that original order and values are retained.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000515 self.assertTrue(x is y)
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000516
517 # Handle evil mutator
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000518 for match in (True, False):
519 d = deque(['ab'])
520 d.extend([MutateCmp(d, match), 'c'])
521 self.assertRaises(IndexError, d.remove, 'c')
522 self.assertEqual(d, deque())
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000523
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000524 def test_repr(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000525 d = deque(range(200))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000526 e = eval(repr(d))
527 self.assertEqual(list(d), list(e))
528 d.append(d)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000529 self.assertIn('...', repr(d))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000530
531 def test_print(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000532 d = deque(range(200))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000533 d.append(d)
Raymond Hettingera435c532004-07-09 04:10:20 +0000534 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000535 support.unlink(support.TESTFN)
536 fo = open(support.TESTFN, "w")
Christian Heimescc47b052008-03-25 14:56:36 +0000537 print(d, file=fo, end='')
Raymond Hettingera435c532004-07-09 04:10:20 +0000538 fo.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000539 fo = open(support.TESTFN, "r")
Raymond Hettingera435c532004-07-09 04:10:20 +0000540 self.assertEqual(fo.read(), repr(d))
541 finally:
542 fo.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000543 support.unlink(support.TESTFN)
Raymond Hettingera435c532004-07-09 04:10:20 +0000544
545 def test_init(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000546 self.assertRaises(TypeError, deque, 'abc', 2, 3);
Raymond Hettingera435c532004-07-09 04:10:20 +0000547 self.assertRaises(TypeError, deque, 1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000548
549 def test_hash(self):
550 self.assertRaises(TypeError, hash, deque('abc'))
551
552 def test_long_steadystate_queue_popleft(self):
553 for size in (0, 1, 2, 100, 1000):
Guido van Rossum805365e2007-05-07 22:24:25 +0000554 d = deque(range(size))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000555 append, pop = d.append, d.popleft
Guido van Rossum805365e2007-05-07 22:24:25 +0000556 for i in range(size, BIG):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000557 append(i)
558 x = pop()
559 if x != i - size:
560 self.assertEqual(x, i-size)
Guido van Rossum805365e2007-05-07 22:24:25 +0000561 self.assertEqual(list(d), list(range(BIG-size, BIG)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000562
563 def test_long_steadystate_queue_popright(self):
564 for size in (0, 1, 2, 100, 1000):
Guido van Rossum805365e2007-05-07 22:24:25 +0000565 d = deque(reversed(range(size)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000566 append, pop = d.appendleft, d.pop
Guido van Rossum805365e2007-05-07 22:24:25 +0000567 for i in range(size, BIG):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000568 append(i)
569 x = pop()
570 if x != i - size:
571 self.assertEqual(x, i-size)
Guido van Rossum805365e2007-05-07 22:24:25 +0000572 self.assertEqual(list(reversed(list(d))),
573 list(range(BIG-size, BIG)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000574
575 def test_big_queue_popleft(self):
576 pass
577 d = deque()
578 append, pop = d.append, d.popleft
Guido van Rossum805365e2007-05-07 22:24:25 +0000579 for i in range(BIG):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000580 append(i)
Guido van Rossum805365e2007-05-07 22:24:25 +0000581 for i in range(BIG):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000582 x = pop()
583 if x != i:
584 self.assertEqual(x, i)
585
586 def test_big_queue_popright(self):
587 d = deque()
588 append, pop = d.appendleft, d.pop
Guido van Rossum805365e2007-05-07 22:24:25 +0000589 for i in range(BIG):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000590 append(i)
Guido van Rossum805365e2007-05-07 22:24:25 +0000591 for i in range(BIG):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000592 x = pop()
593 if x != i:
594 self.assertEqual(x, i)
595
596 def test_big_stack_right(self):
597 d = deque()
598 append, pop = d.append, d.pop
Guido van Rossum805365e2007-05-07 22:24:25 +0000599 for i in range(BIG):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000600 append(i)
Guido van Rossum805365e2007-05-07 22:24:25 +0000601 for i in reversed(range(BIG)):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000602 x = pop()
603 if x != i:
604 self.assertEqual(x, i)
605 self.assertEqual(len(d), 0)
606
607 def test_big_stack_left(self):
608 d = deque()
609 append, pop = d.appendleft, d.popleft
Guido van Rossum805365e2007-05-07 22:24:25 +0000610 for i in range(BIG):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000611 append(i)
Guido van Rossum805365e2007-05-07 22:24:25 +0000612 for i in reversed(range(BIG)):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000613 x = pop()
614 if x != i:
615 self.assertEqual(x, i)
616 self.assertEqual(len(d), 0)
617
618 def test_roundtrip_iter_init(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000619 d = deque(range(200))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000620 e = deque(d)
621 self.assertNotEqual(id(d), id(e))
622 self.assertEqual(list(d), list(e))
623
624 def test_pickle(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000625 d = deque(range(200))
Hirokazu Yamamoto801f9d32008-12-27 04:21:44 +0000626 for i in range(pickle.HIGHEST_PROTOCOL + 1):
Raymond Hettinger952f8802004-11-09 07:27:35 +0000627 s = pickle.dumps(d, i)
628 e = pickle.loads(s)
629 self.assertNotEqual(id(d), id(e))
630 self.assertEqual(list(d), list(e))
631
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000632## def test_pickle_recursive(self):
633## d = deque('abc')
634## d.append(d)
Hirokazu Yamamoto801f9d32008-12-27 04:21:44 +0000635## for i in range(pickle.HIGHEST_PROTOCOL + 1):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000636## e = pickle.loads(pickle.dumps(d, i))
637## self.assertNotEqual(id(d), id(e))
638## self.assertEqual(id(e), id(e[-1]))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000639
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000640 def test_iterator_pickle(self):
641 data = deque(range(200))
Serhiy Storchakabad12572014-12-15 14:03:42 +0200642 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
643 it = itorg = iter(data)
644 d = pickle.dumps(it, proto)
645 it = pickle.loads(d)
646 self.assertEqual(type(itorg), type(it))
647 self.assertEqual(list(it), list(data))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000648
Serhiy Storchakabad12572014-12-15 14:03:42 +0200649 it = pickle.loads(d)
650 next(it)
651 d = pickle.dumps(it, proto)
652 self.assertEqual(list(it), list(data)[1:])
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000653
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000654 def test_deepcopy(self):
655 mut = [10]
656 d = deque([mut])
657 e = copy.deepcopy(d)
658 self.assertEqual(list(d), list(e))
659 mut[0] = 11
660 self.assertNotEqual(id(d), id(e))
661 self.assertNotEqual(list(d), list(e))
662
663 def test_copy(self):
664 mut = [10]
665 d = deque([mut])
666 e = copy.copy(d)
667 self.assertEqual(list(d), list(e))
668 mut[0] = 11
669 self.assertNotEqual(id(d), id(e))
670 self.assertEqual(list(d), list(e))
671
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700672 def test_copy_method(self):
673 mut = [10]
674 d = deque([mut])
675 e = d.copy()
676 self.assertEqual(list(d), list(e))
677 mut[0] = 11
678 self.assertNotEqual(id(d), id(e))
679 self.assertEqual(list(d), list(e))
680
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000681 def test_reversed(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000682 for s in ('abcd', range(2000)):
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000683 self.assertEqual(list(reversed(deque(s))), list(reversed(s)))
684
Raymond Hettingerbadf5d82014-06-14 20:41:22 -0700685 def test_reversed_new(self):
686 klass = type(reversed(deque()))
687 for s in ('abcd', range(2000)):
688 self.assertEqual(list(klass(deque(s))), list(reversed(s)))
689
Tim Peters10c7e862004-10-01 02:01:04 +0000690 def test_gc_doesnt_blowup(self):
691 import gc
692 # This used to assert-fail in deque_traverse() under a debug
693 # build, or run wild with a NULL pointer in a release build.
694 d = deque()
Guido van Rossum805365e2007-05-07 22:24:25 +0000695 for i in range(100):
Tim Peters10c7e862004-10-01 02:01:04 +0000696 d.append(1)
697 gc.collect()
698
Antoine Pitrou7ddda782009-01-01 15:35:33 +0000699 def test_container_iterator(self):
700 # Bug #3680: tp_traverse was not implemented for deque iterator objects
701 class C(object):
702 pass
703 for i in range(2):
704 obj = C()
705 ref = weakref.ref(obj)
706 if i == 0:
707 container = deque([obj, 1])
708 else:
709 container = reversed(deque([obj, 1]))
710 obj.x = iter(container)
711 del obj, container
712 gc.collect()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000713 self.assertTrue(ref() is None, "Cycle was not collected")
Antoine Pitrou7ddda782009-01-01 15:35:33 +0000714
Jesus Cea16e2fca2012-08-03 14:49:42 +0200715 check_sizeof = support.check_sizeof
716
717 @support.cpython_only
718 def test_sizeof(self):
Raymond Hettingerdaf57f22015-02-26 23:21:29 -0800719 BLOCKLEN = 64
Jesus Cea1659b752012-08-03 14:52:12 +0200720 basesize = support.calcobjsize('2P4nlP')
Jesus Cea16e2fca2012-08-03 14:49:42 +0200721 blocksize = struct.calcsize('2P%dP' % BLOCKLEN)
722 self.assertEqual(object.__sizeof__(deque()), basesize)
723 check = self.check_sizeof
724 check(deque(), basesize + blocksize)
725 check(deque('a'), basesize + blocksize)
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700726 check(deque('a' * (BLOCKLEN - 1)), basesize + blocksize)
727 check(deque('a' * BLOCKLEN), basesize + 2 * blocksize)
Jesus Cea16e2fca2012-08-03 14:49:42 +0200728 check(deque('a' * (42 * BLOCKLEN)), basesize + 43 * blocksize)
729
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000730class TestVariousIteratorArgs(unittest.TestCase):
731
732 def test_constructor(self):
Guido van Rossum805365e2007-05-07 22:24:25 +0000733 for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
Walter Dörwald09a3f2c2005-03-22 22:43:28 +0000734 for g in (seq_tests.Sequence, seq_tests.IterFunc,
735 seq_tests.IterGen, seq_tests.IterFuncStop,
736 seq_tests.itermulti, seq_tests.iterfunc):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000737 self.assertEqual(list(deque(g(s))), list(g(s)))
Walter Dörwald09a3f2c2005-03-22 22:43:28 +0000738 self.assertRaises(TypeError, deque, seq_tests.IterNextOnly(s))
739 self.assertRaises(TypeError, deque, seq_tests.IterNoNext(s))
740 self.assertRaises(ZeroDivisionError, deque, seq_tests.IterGenExc(s))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000741
742 def test_iter_with_altered_data(self):
743 d = deque('abcdefg')
744 it = iter(d)
745 d.pop()
Georg Brandla18af4e2007-04-21 15:47:16 +0000746 self.assertRaises(RuntimeError, next, it)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000747
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000748 def test_runtime_error_on_empty_deque(self):
749 d = deque()
750 it = iter(d)
751 d.append(10)
Georg Brandla18af4e2007-04-21 15:47:16 +0000752 self.assertRaises(RuntimeError, next, it)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000753
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000754class Deque(deque):
755 pass
756
Raymond Hettinger952f8802004-11-09 07:27:35 +0000757class DequeWithBadIter(deque):
758 def __iter__(self):
759 raise TypeError
760
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000761class TestSubclass(unittest.TestCase):
762
763 def test_basics(self):
Christian Heimes38053212007-12-14 01:24:44 +0000764 d = Deque(range(25))
765 d.__init__(range(200))
Guido van Rossum805365e2007-05-07 22:24:25 +0000766 for i in range(200, 400):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000767 d.append(i)
Guido van Rossum805365e2007-05-07 22:24:25 +0000768 for i in reversed(range(-200, 0)):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000769 d.appendleft(i)
Guido van Rossum805365e2007-05-07 22:24:25 +0000770 self.assertEqual(list(d), list(range(-200, 400)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000771 self.assertEqual(len(d), 600)
772
Guido van Rossum805365e2007-05-07 22:24:25 +0000773 left = [d.popleft() for i in range(250)]
774 self.assertEqual(left, list(range(-200, 50)))
775 self.assertEqual(list(d), list(range(50, 400)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000776
Guido van Rossum805365e2007-05-07 22:24:25 +0000777 right = [d.pop() for i in range(250)]
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000778 right.reverse()
Guido van Rossum805365e2007-05-07 22:24:25 +0000779 self.assertEqual(right, list(range(150, 400)))
780 self.assertEqual(list(d), list(range(50, 150)))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000781
782 d.clear()
783 self.assertEqual(len(d), 0)
784
785 def test_copy_pickle(self):
786
787 d = Deque('abc')
788
789 e = d.__copy__()
790 self.assertEqual(type(d), type(e))
791 self.assertEqual(list(d), list(e))
792
793 e = Deque(d)
794 self.assertEqual(type(d), type(e))
795 self.assertEqual(list(d), list(e))
796
Serhiy Storchakabad12572014-12-15 14:03:42 +0200797 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
798 s = pickle.dumps(d, proto)
799 e = pickle.loads(s)
800 self.assertNotEqual(id(d), id(e))
801 self.assertEqual(type(d), type(e))
802 self.assertEqual(list(d), list(e))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000803
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000804 d = Deque('abcde', maxlen=4)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000805
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000806 e = d.__copy__()
807 self.assertEqual(type(d), type(e))
808 self.assertEqual(list(d), list(e))
809
810 e = Deque(d)
811 self.assertEqual(type(d), type(e))
812 self.assertEqual(list(d), list(e))
813
Serhiy Storchakabad12572014-12-15 14:03:42 +0200814 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
815 s = pickle.dumps(d, proto)
816 e = pickle.loads(s)
817 self.assertNotEqual(id(d), id(e))
818 self.assertEqual(type(d), type(e))
819 self.assertEqual(list(d), list(e))
Raymond Hettinger952f8802004-11-09 07:27:35 +0000820
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000821## def test_pickle(self):
822## d = Deque('abc')
823## d.append(d)
824##
825## e = pickle.loads(pickle.dumps(d))
826## self.assertNotEqual(id(d), id(e))
827## self.assertEqual(type(d), type(e))
828## dd = d.pop()
829## ee = e.pop()
830## self.assertEqual(id(e), id(ee))
831## self.assertEqual(d, e)
832##
833## d.x = d
834## e = pickle.loads(pickle.dumps(d))
835## self.assertEqual(id(e), id(e.x))
836##
837## d = DequeWithBadIter('abc')
838## self.assertRaises(TypeError, pickle.dumps, d)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000839
Raymond Hettinger691d8052004-05-30 07:26:47 +0000840 def test_weakref(self):
841 d = deque('gallahad')
Antoine Pitrou7ddda782009-01-01 15:35:33 +0000842 p = weakref.proxy(d)
Raymond Hettinger691d8052004-05-30 07:26:47 +0000843 self.assertEqual(str(p), str(d))
844 d = None
845 self.assertRaises(ReferenceError, str, p)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000846
Armin Rigo974d7572004-10-02 13:59:34 +0000847 def test_strange_subclass(self):
848 class X(deque):
849 def __iter__(self):
850 return iter([])
851 d1 = X([1,2,3])
852 d2 = X([4,5,6])
853 d1 == d2 # not clear if this is supposed to be True or False,
854 # but it used to give a SystemError
855
Thomas Woutersb2137042007-02-01 18:02:27 +0000856
857class SubclassWithKwargs(deque):
858 def __init__(self, newarg=1):
859 deque.__init__(self)
860
861class TestSubclassWithKwargs(unittest.TestCase):
862 def test_subclass_with_kwargs(self):
863 # SF bug #1486663 -- this used to erroneously raise a TypeError
864 SubclassWithKwargs(newarg=1)
865
Raymond Hettinger067bbba2015-04-01 08:11:09 -0700866class TestSequence(seq_tests.CommonTest):
867 type2test = deque
868
869 def test_getitem(self):
870 # For now, bypass tests that require slicing
871 pass
872
873 def test_getslice(self):
874 # For now, bypass tests that require slicing
875 pass
876
877 def test_subscript(self):
878 # For now, bypass tests that require slicing
879 pass
880
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000881#==============================================================================
882
Raymond Hettinger738ec902004-02-29 02:15:56 +0000883libreftest = """
884Example from the Library Reference: Doc/lib/libcollections.tex
885
886>>> from collections import deque
887>>> d = deque('ghi') # make a new deque with three items
888>>> for elem in d: # iterate over the deque's elements
Guido van Rossum7131f842007-02-09 20:13:25 +0000889... print(elem.upper())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000890G
891H
892I
893>>> d.append('j') # add a new entry to the right side
894>>> d.appendleft('f') # add a new entry to the left side
895>>> d # show the representation of the deque
896deque(['f', 'g', 'h', 'i', 'j'])
897>>> d.pop() # return and remove the rightmost item
898'j'
899>>> d.popleft() # return and remove the leftmost item
900'f'
901>>> list(d) # list the contents of the deque
902['g', 'h', 'i']
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000903>>> d[0] # peek at leftmost item
Raymond Hettinger738ec902004-02-29 02:15:56 +0000904'g'
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000905>>> d[-1] # peek at rightmost item
Raymond Hettinger738ec902004-02-29 02:15:56 +0000906'i'
907>>> list(reversed(d)) # list the contents of a deque in reverse
908['i', 'h', 'g']
909>>> 'h' in d # search the deque
910True
911>>> d.extend('jkl') # add multiple elements at once
912>>> d
913deque(['g', 'h', 'i', 'j', 'k', 'l'])
914>>> d.rotate(1) # right rotation
915>>> d
916deque(['l', 'g', 'h', 'i', 'j', 'k'])
917>>> d.rotate(-1) # left rotation
918>>> d
919deque(['g', 'h', 'i', 'j', 'k', 'l'])
920>>> deque(reversed(d)) # make a new deque in reverse order
921deque(['l', 'k', 'j', 'i', 'h', 'g'])
922>>> d.clear() # empty the deque
923>>> d.pop() # cannot pop from an empty deque
924Traceback (most recent call last):
925 File "<pyshell#6>", line 1, in -toplevel-
926 d.pop()
927IndexError: pop from an empty deque
928
929>>> d.extendleft('abc') # extendleft() reverses the input order
930>>> d
931deque(['c', 'b', 'a'])
932
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000933
934
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000935>>> def delete_nth(d, n):
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000936... d.rotate(-n)
937... d.popleft()
938... d.rotate(n)
939...
940>>> d = deque('abcdef')
941>>> delete_nth(d, 2) # remove the entry at d[2]
942>>> d
943deque(['a', 'b', 'd', 'e', 'f'])
944
945
946
947>>> def roundrobin(*iterables):
948... pending = deque(iter(i) for i in iterables)
949... while pending:
950... task = pending.popleft()
951... try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000952... yield next(task)
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000953... except StopIteration:
954... continue
955... pending.append(task)
956...
957
958>>> for value in roundrobin('abc', 'd', 'efgh'):
Guido van Rossum7131f842007-02-09 20:13:25 +0000959... print(value)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960...
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000961a
962d
963e
964b
965f
966c
967g
968h
969
970
971>>> def maketree(iterable):
972... d = deque(iterable)
973... while len(d) > 1:
974... pair = [d.popleft(), d.popleft()]
975... d.append(pair)
976... return list(d)
977...
Guido van Rossum7131f842007-02-09 20:13:25 +0000978>>> print(maketree('abcdefgh'))
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000979[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
980
Raymond Hettinger738ec902004-02-29 02:15:56 +0000981"""
982
983
984#==============================================================================
985
986__test__ = {'libreftest' : libreftest}
987
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000988def test_main(verbose=None):
989 import sys
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000990 test_classes = (
991 TestBasic,
992 TestVariousIteratorArgs,
993 TestSubclass,
Thomas Woutersb2137042007-02-01 18:02:27 +0000994 TestSubclassWithKwargs,
Raymond Hettinger067bbba2015-04-01 08:11:09 -0700995 TestSequence,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000996 )
997
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000998 support.run_unittest(*test_classes)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000999
1000 # verify reference counting
1001 if verbose and hasattr(sys, "gettotalrefcount"):
1002 import gc
1003 counts = [None] * 5
Guido van Rossum805365e2007-05-07 22:24:25 +00001004 for i in range(len(counts)):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001005 support.run_unittest(*test_classes)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001006 gc.collect()
1007 counts[i] = sys.gettotalrefcount()
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001008 print(counts)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001009
Raymond Hettinger738ec902004-02-29 02:15:56 +00001010 # doctests
1011 from test import test_deque
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001012 support.run_doctest(test_deque, verbose)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001013
1014if __name__ == "__main__":
1015 test_main(verbose=True)