Debian Codegraph @

Lib/test/test_unpack_ex.py

raw
1 # Tests for extended unpacking, starred expressions.
2
3 import doctest
4 import unittest
5
6
7 doctests = """
8
9 Unpack tuple
10
11 >>> t = (1, 2, 3)
12 >>> a, *b, c = t
13 >>> a == 1 and b == [2] and c == 3
14 True
15
16 Unpack list
17
18 >>> l = [4, 5, 6]
19 >>> a, *b = l
20 >>> a == 4 and b == [5, 6]
21 True
22
23 Unpack implied tuple
24
25 >>> *a, = 7, 8, 9
26 >>> a == [7, 8, 9]
27 True
28
29 Unpack nested implied tuple
30
31 >>> [*[*a]] = [[7,8,9]]
32 >>> a == [[7,8,9]]
33 True
34
35 Unpack string... fun!
36
37 >>> a, *b = 'one'
38 >>> a == 'o' and b == ['n', 'e']
39 True
40
41 Unpack long sequence
42
43 >>> a, b, c, *d, e, f, g = range(10)
44 >>> (a, b, c, d, e, f, g) == (0, 1, 2, [3, 4, 5, 6], 7, 8, 9)
45 True
46
47 Unpack short sequence
48
49 >>> a, *b, c = (1, 2)
50 >>> a == 1 and c == 2 and b == []
51 True
52
53 Unpack generic sequence
54
55 >>> class Seq:
56 ... def __getitem__(self, i):
57 ... if i >= 0 and i < 3: return i
58 ... raise IndexError
59 ...
60 >>> a, *b = Seq()
61 >>> a == 0 and b == [1, 2]
62 True
63
64 Unpack in for statement
65
66 >>> for a, *b, c in [(1,2,3), (4,5,6,7)]:
67 ... print(a, b, c)
68 ...
69 1 [2] 3
70 4 [5, 6] 7
71
72 Unpack in list
73
74 >>> [a, *b, c] = range(5)
75 >>> a == 0 and b == [1, 2, 3] and c == 4
76 True
77
78 Multiple targets
79
80 >>> a, *b, c = *d, e = range(5)
81 >>> a == 0 and b == [1, 2, 3] and c == 4 and d == [0, 1, 2, 3] and e == 4
82 True
83
84 Assignment unpacking
85
86 >>> a, b, *c = range(5)
87 >>> a, b, c
88 (0, 1, [2, 3, 4])
89 >>> *a, b, c = a, b, *c
90 >>> a, b, c
91 ([0, 1, 2], 3, 4)
92
93 Set display element unpacking
94
95 >>> a = [1, 2, 3]
96 >>> sorted({1, *a, 0, 4})
97 [0, 1, 2, 3, 4]
98
99 >>> {1, *1, 0, 4}
100 Traceback (most recent call last):
101 ...
102 TypeError: 'int' object is not iterable
103
104 Dict display element unpacking
105
106 >>> kwds = {'z': 0, 'w': 12}
107 >>> sorted({'x': 1, 'y': 2, **kwds}.items())
108 [('w', 12), ('x', 1), ('y', 2), ('z', 0)]
109
110 >>> sorted({**{'x': 1}, 'y': 2, **{'z': 3}}.items())
111 [('x', 1), ('y', 2), ('z', 3)]
112
113 >>> sorted({**{'x': 1}, 'y': 2, **{'x': 3}}.items())
114 [('x', 3), ('y', 2)]
115
116 >>> sorted({**{'x': 1}, **{'x': 3}, 'x': 4}.items())
117 [('x', 4)]
118
119 >>> {**{}}
120 {}
121
122 >>> a = {}
123 >>> {**a}[0] = 1
124 >>> a
125 {}
126
127 >>> {**1}
128 Traceback (most recent call last):
129 ...
130 TypeError: 'int' object is not a mapping
131
132 >>> {**[]}
133 Traceback (most recent call last):
134 ...
135 TypeError: 'list' object is not a mapping
136
137 >>> len(eval("{" + ", ".join("**{{{}: {}}}".format(i, i)
138 ... for i in range(1000)) + "}"))
139 1000
140
141 >>> {0:1, **{0:2}, 0:3, 0:4}
142 {0: 4}
143
144 List comprehension element unpacking
145
146 >>> a, b, c = [0, 1, 2], 3, 4
147 >>> [*a, b, c]
148 [0, 1, 2, 3, 4]
149
150 >>> l = [a, (3, 4), {5}, {6: None}, (i for i in range(7, 10))]
151 >>> [*item for item in l]
152 Traceback (most recent call last):
153 ...
154 SyntaxError: iterable unpacking cannot be used in comprehension
155
156 >>> [*[0, 1] for i in range(10)]
157 Traceback (most recent call last):
158 ...
159 SyntaxError: iterable unpacking cannot be used in comprehension
160
161 >>> [*'a' for i in range(10)]
162 Traceback (most recent call last):
163 ...
164 SyntaxError: iterable unpacking cannot be used in comprehension
165
166 >>> [*[] for i in range(10)]
167 Traceback (most recent call last):
168 ...
169 SyntaxError: iterable unpacking cannot be used in comprehension
170
171 >>> {**{} for a in [1]}
172 Traceback (most recent call last):
173 ...
174 SyntaxError: dict unpacking cannot be used in dict comprehension
175
176 # Pegen is better here.
177 # Generator expression in function arguments
178
179 # >>> list(*x for x in (range(5) for i in range(3)))
180 # Traceback (most recent call last):
181 # ...
182 # list(*x for x in (range(5) for i in range(3)))
183 # ^
184 # SyntaxError: invalid syntax
185
186 >>> dict(**x for x in [{1:2}])
187 Traceback (most recent call last):
188 ...
189 dict(**x for x in [{1:2}])
190 ^
191 SyntaxError: invalid syntax
192
193 Iterable argument unpacking
194
195 >>> print(*[1], *[2], 3)
196 1 2 3
197
198 Make sure that they don't corrupt the passed-in dicts.
199
200 >>> def f(x, y):
201 ... print(x, y)
202 ...
203 >>> original_dict = {'x': 1}
204 >>> f(**original_dict, y=2)
205 1 2
206 >>> original_dict
207 {'x': 1}
208
209 Now for some failures
210
211 Make sure the raised errors are right for keyword argument unpackings
212
213 >>> from collections.abc import MutableMapping
214 >>> class CrazyDict(MutableMapping):
215 ... def __init__(self):
216 ... self.d = {}
217 ...
218 ... def __iter__(self):
219 ... for x in self.d.__iter__():
220 ... if x == 'c':
221 ... self.d['z'] = 10
222 ... yield x
223 ...
224 ... def __getitem__(self, k):
225 ... return self.d[k]
226 ...
227 ... def __len__(self):
228 ... return len(self.d)
229 ...
230 ... def __setitem__(self, k, v):
231 ... self.d[k] = v
232 ...
233 ... def __delitem__(self, k):
234 ... del self.d[k]
235 ...
236 >>> d = CrazyDict()
237 >>> d.d = {chr(ord('a') + x): x for x in range(5)}
238 >>> e = {**d}
239 Traceback (most recent call last):
240 ...
241 RuntimeError: dictionary changed size during iteration
242
243 >>> d.d = {chr(ord('a') + x): x for x in range(5)}
244 >>> def f(**kwargs): print(kwargs)
245 >>> f(**d)
246 Traceback (most recent call last):
247 ...
248 RuntimeError: dictionary changed size during iteration
249
250 Overridden parameters
251
252 >>> f(x=5, **{'x': 3}, y=2)
253 Traceback (most recent call last):
254 ...
255 TypeError: test.test_unpack_ex.f() got multiple values for keyword argument 'x'
256
257 >>> f(**{'x': 3}, x=5, y=2)
258 Traceback (most recent call last):
259 ...
260 TypeError: test.test_unpack_ex.f() got multiple values for keyword argument 'x'
261
262 >>> f(**{'x': 3}, **{'x': 5}, y=2)
263 Traceback (most recent call last):
264 ...
265 TypeError: test.test_unpack_ex.f() got multiple values for keyword argument 'x'
266
267 >>> f(x=5, **{'x': 3}, **{'x': 2})
268 Traceback (most recent call last):
269 ...
270 TypeError: test.test_unpack_ex.f() got multiple values for keyword argument 'x'
271
272 >>> f(**{1: 3}, **{1: 5})
273 Traceback (most recent call last):
274 ...
275 TypeError: test.test_unpack_ex.f() got multiple values for keyword argument '1'
276
277 Unpacking non-sequence
278
279 >>> a, *b = 7
280 Traceback (most recent call last):
281 ...
282 TypeError: cannot unpack non-iterable int object
283
284 Unpacking sequence too short
285
286 >>> a, *b, c, d, e = Seq()
287 Traceback (most recent call last):
288 ...
289 ValueError: not enough values to unpack (expected at least 4, got 3)
290
291 Unpacking sequence too short and target appears last
292
293 >>> a, b, c, d, *e = Seq()
294 Traceback (most recent call last):
295 ...
296 ValueError: not enough values to unpack (expected at least 4, got 3)
297
298 Unpacking a sequence where the test for too long raises a different kind of
299 error
300
301 >>> class BozoError(Exception):
302 ... pass
303 ...
304 >>> class BadSeq:
305 ... def __getitem__(self, i):
306 ... if i >= 0 and i < 3:
307 ... return i
308 ... elif i == 3:
309 ... raise BozoError
310 ... else:
311 ... raise IndexError
312 ...
313
314 Trigger code while not expecting an IndexError (unpack sequence too long, wrong
315 error)
316
317 >>> a, *b, c, d, e = BadSeq()
318 Traceback (most recent call last):
319 ...
320 test.test_unpack_ex.BozoError
321
322 Now some general starred expressions (all fail).
323
324 >>> a, *b, c, *d, e = range(10) # doctest:+ELLIPSIS
325 Traceback (most recent call last):
326 ...
327 SyntaxError: multiple starred expressions in assignment
328
329 >>> [*b, *c] = range(10) # doctest:+ELLIPSIS
330 Traceback (most recent call last):
331 ...
332 SyntaxError: multiple starred expressions in assignment
333
334 >>> a,*b,*c,*d = range(4) # doctest:+ELLIPSIS
335 Traceback (most recent call last):
336 ...
337 SyntaxError: multiple starred expressions in assignment
338
339 >>> *a = range(10) # doctest:+ELLIPSIS
340 Traceback (most recent call last):
341 ...
342 SyntaxError: starred assignment target must be in a list or tuple
343
344 >>> *a # doctest:+ELLIPSIS
345 Traceback (most recent call last):
346 ...
347 SyntaxError: can't use starred expression here
348
349 >>> *1 # doctest:+ELLIPSIS
350 Traceback (most recent call last):
351 ...
352 SyntaxError: can't use starred expression here
353
354 >>> x = *a # doctest:+ELLIPSIS
355 Traceback (most recent call last):
356 ...
357 SyntaxError: can't use starred expression here
358
359 >>> (*x),y = 1, 2 # doctest:+ELLIPSIS
360 Traceback (most recent call last):
361 ...
362 SyntaxError: cannot use starred expression here
363
364 >>> (((*x))),y = 1, 2 # doctest:+ELLIPSIS
365 Traceback (most recent call last):
366 ...
367 SyntaxError: cannot use starred expression here
368
369 >>> z,(*x),y = 1, 2, 4 # doctest:+ELLIPSIS
370 Traceback (most recent call last):
371 ...
372 SyntaxError: cannot use starred expression here
373
374 >>> z,(*x) = 1, 2 # doctest:+ELLIPSIS
375 Traceback (most recent call last):
376 ...
377 SyntaxError: cannot use starred expression here
378
379 >>> ((*x),y) = 1, 2 # doctest:+ELLIPSIS
380 Traceback (most recent call last):
381 ...
382 SyntaxError: cannot use starred expression here
383
384 Some size constraints (all fail.)
385
386 >>> s = ", ".join("a%d" % i for i in range(1<<8)) + ", *rest = range((1<<8) + 1)"
387 >>> compile(s, 'test', 'exec') # doctest:+ELLIPSIS
388 Traceback (most recent call last):
389 ...
390 SyntaxError: too many expressions in star-unpacking assignment
391
392 >>> s = ", ".join("a%d" % i for i in range((1<<8) + 1)) + ", *rest = range((1<<8) + 2)"
393 >>> compile(s, 'test', 'exec') # doctest:+ELLIPSIS
394 Traceback (most recent call last):
395 ...
396 SyntaxError: too many expressions in star-unpacking assignment
397
398 (there is an additional limit, on the number of expressions after the
399 '*rest', but it's 1<<24 and testing it takes too much memory.)
400
401 """
402
403 __test__ = {'doctests' : doctests}
404
405 def load_tests(loader, tests, pattern):
406 tests.addTest(doctest.DocTestSuite())
407 return tests
408
409
410 if __name__ == "__main__":
411 unittest.main()