Debian Codegraph @

Lib/test/test_listcomps.py

raw
1 import doctest
2 import textwrap
3 import traceback
4 import types
5 import unittest
6
7 from test.support import BrokenIter
8
9
10 doctests = """
11 ########### Tests borrowed from or inspired by test_genexps.py ############
12
13 Test simple loop with conditional
14
15 >>> sum([i*i for i in range(100) if i&1 == 1])
16 166650
17
18 Test simple nesting
19
20 >>> [(i,j) for i in range(3) for j in range(4)]
21 [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]
22
23 Test nesting with the inner expression dependent on the outer
24
25 >>> [(i,j) for i in range(4) for j in range(i)]
26 [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]
27
28 Test the idiom for temporary variable assignment in comprehensions.
29
30 >>> [j*j for i in range(4) for j in [i+1]]
31 [1, 4, 9, 16]
32 >>> [j*k for i in range(4) for j in [i+1] for k in [j+1]]
33 [2, 6, 12, 20]
34 >>> [j*k for i in range(4) for j, k in [(i+1, i+2)]]
35 [2, 6, 12, 20]
36
37 Not assignment
38
39 >>> [i*i for i in [*range(4)]]
40 [0, 1, 4, 9]
41 >>> [i*i for i in (*range(4),)]
42 [0, 1, 4, 9]
43
44 Make sure the induction variable is not exposed
45
46 >>> i = 20
47 >>> sum([i*i for i in range(100)])
48 328350
49
50 >>> i
51 20
52
53 Verify that syntax error's are raised for listcomps used as lvalues
54
55 >>> [y for y in (1,2)] = 10 # doctest: +IGNORE_EXCEPTION_DETAIL
56 Traceback (most recent call last):
57 ...
58 SyntaxError: ...
59
60 >>> [y for y in (1,2)] += 10 # doctest: +IGNORE_EXCEPTION_DETAIL
61 Traceback (most recent call last):
62 ...
63 SyntaxError: ...
64
65
66 ########### Tests borrowed from or inspired by test_generators.py ############
67
68 Make a nested list comprehension that acts like range()
69
70 >>> def frange(n):
71 ... return [i for i in range(n)]
72 >>> frange(10)
73 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
74
75 Same again, only as a lambda expression instead of a function definition
76
77 >>> lrange = lambda n: [i for i in range(n)]
78 >>> lrange(10)
79 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
80
81 Generators can call other generators:
82
83 >>> def grange(n):
84 ... for x in [i for i in range(n)]:
85 ... yield x
86 >>> list(grange(5))
87 [0, 1, 2, 3, 4]
88
89
90 Make sure that None is a valid return value
91
92 >>> [None for i in range(10)]
93 [None, None, None, None, None, None, None, None, None, None]
94
95 """
96
97
98 class ListComprehensionTest(unittest.TestCase):
99 def _check_in_scopes(self, code, outputs=None, ns=None, scopes=None, raises=(),
100 exec_func=exec):
101 code = textwrap.dedent(code)
102 scopes = scopes or ["module", "class", "function"]
103 for scope in scopes:
104 with self.subTest(scope=scope):
105 if scope == "class":
106 newcode = textwrap.dedent("""
107 class _C:
108 {code}
109 """).format(code=textwrap.indent(code, " "))
110 def get_output(moddict, name):
111 return getattr(moddict["_C"], name)
112 elif scope == "function":
113 newcode = textwrap.dedent("""
114 def _f():
115 {code}
116 return locals()
117 _out = _f()
118 """).format(code=textwrap.indent(code, " "))
119 def get_output(moddict, name):
120 return moddict["_out"][name]
121 else:
122 newcode = code
123 def get_output(moddict, name):
124 return moddict[name]
125 newns = ns.copy() if ns else {}
126 try:
127 exec_func(newcode, newns)
128 except raises as e:
129 # We care about e.g. NameError vs UnboundLocalError
130 self.assertIs(type(e), raises)
131 else:
132 for k, v in (outputs or {}).items():
133 self.assertEqual(get_output(newns, k), v, k)
134
135 def test_lambdas_with_iteration_var_as_default(self):
136 code = """
137 items = [(lambda i=i: i) for i in range(5)]
138 y = [x() for x in items]
139 """
140 outputs = {"y": [0, 1, 2, 3, 4]}
141 self._check_in_scopes(code, outputs)
142
143 def test_lambdas_with_free_var(self):
144 code = """
145 items = [(lambda: i) for i in range(5)]
146 y = [x() for x in items]
147 """
148 outputs = {"y": [4, 4, 4, 4, 4]}
149 self._check_in_scopes(code, outputs)
150
151 def test_class_scope_free_var_with_class_cell(self):
152 class C:
153 def method(self):
154 super()
155 return __class__
156 items = [(lambda: i) for i in range(5)]
157 y = [x() for x in items]
158
159 self.assertEqual(C.y, [4, 4, 4, 4, 4])
160 self.assertIs(C().method(), C)
161
162 def test_references_super(self):
163 code = """
164 res = [super for x in [1]]
165 """
166 self._check_in_scopes(code, outputs={"res": [super]})
167
168 def test_references___class__(self):
169 code = """
170 res = [__class__ for x in [1]]
171 """
172 self._check_in_scopes(code, raises=NameError)
173
174 def test_references___class___nested(self):
175 code = """
176 res = [(lambda: __class__)() for _ in [1]]
177 """
178 self._check_in_scopes(code, raises=NameError)
179
180 def test_references___class___nested_used(self):
181 class _C:
182 res = [lambda: __class__ for _ in [1]]
183 self.assertIs(_C.res[0](), _C)
184
185 def test_references___class___defined(self):
186 code = """
187 __class__ = 2
188 res = [__class__ for x in [1]]
189 """
190 self._check_in_scopes(
191 code, outputs={"res": [2]}, scopes=["module", "function"])
192 self._check_in_scopes(code, raises=NameError, scopes=["class"])
193
194 def test_references___class___defined_nested(self):
195 code = """
196 __class__ = 2
197 res = [(lambda: __class__)() for x in [1]]
198 """
199 self._check_in_scopes(
200 code, outputs={"res": [2]}, scopes=["module", "function"])
201 self._check_in_scopes(code, raises=NameError, scopes=["class"])
202
203 def test_references___classdict__(self):
204 code = """
205 class i: [__classdict__ for x in y]
206 """
207 self._check_in_scopes(code, raises=NameError)
208
209 def test_references___classdict___nested(self):
210 class _C:
211 res = [(lambda: __classdict__)() for _ in [1]]
212 self.assertIn("res", _C.res[0])
213
214 def test_references___conditional_annotations__(self):
215 code = """
216 class i: [__conditional_annotations__ for x in y]
217 """
218 self._check_in_scopes(code, raises=NameError)
219
220 def test_references___conditional_annotations___nested(self):
221 code = """
222 class i: [lambda: __conditional_annotations__ for x in y]
223 """
224 self._check_in_scopes(code, raises=NameError)
225
226 def test_references___class___enclosing(self):
227 code = """
228 __class__ = 2
229 class C:
230 res = [__class__ for x in [1]]
231 res = C.res
232 """
233 self._check_in_scopes(code, raises=NameError)
234
235 def test_super_and_class_cell_in_sibling_comps(self):
236 code = """
237 [super for _ in [1]]
238 [__class__ for _ in [1]]
239 """
240 self._check_in_scopes(code, raises=NameError)
241
242 def test_inner_cell_shadows_outer(self):
243 code = """
244 items = [(lambda: i) for i in range(5)]
245 i = 20
246 y = [x() for x in items]
247 """
248 outputs = {"y": [4, 4, 4, 4, 4], "i": 20}
249 self._check_in_scopes(code, outputs)
250
251 def test_inner_cell_shadows_outer_no_store(self):
252 code = """
253 def f(x):
254 return [lambda: x for x in range(x)], x
255 fns, x = f(2)
256 y = [fn() for fn in fns]
257 """
258 outputs = {"y": [1, 1], "x": 2}
259 self._check_in_scopes(code, outputs)
260
261 def test_closure_can_jump_over_comp_scope(self):
262 code = """
263 items = [(lambda: y) for i in range(5)]
264 y = 2
265 z = [x() for x in items]
266 """
267 outputs = {"z": [2, 2, 2, 2, 2]}
268 self._check_in_scopes(code, outputs, scopes=["module", "function"])
269
270 def test_cell_inner_free_outer(self):
271 code = """
272 def f():
273 return [lambda: x for x in (x, [1])[1]]
274 x = ...
275 y = [fn() for fn in f()]
276 """
277 outputs = {"y": [1]}
278 self._check_in_scopes(code, outputs, scopes=["module", "function"])
279
280 def test_free_inner_cell_outer(self):
281 code = """
282 g = 2
283 def f():
284 return g
285 y = [g for x in [1]]
286 """
287 outputs = {"y": [2]}
288 self._check_in_scopes(code, outputs, scopes=["module", "function"])
289 self._check_in_scopes(code, scopes=["class"], raises=NameError)
290
291 def test_inner_cell_shadows_outer_redefined(self):
292 code = """
293 y = 10
294 items = [(lambda: y) for y in range(5)]
295 x = y
296 y = 20
297 out = [z() for z in items]
298 """
299 outputs = {"x": 10, "out": [4, 4, 4, 4, 4]}
300 self._check_in_scopes(code, outputs)
301
302 def test_shadows_outer_cell(self):
303 code = """
304 def inner():
305 return g
306 [g for g in range(5)]
307 x = inner()
308 """
309 outputs = {"x": -1}
310 self._check_in_scopes(code, outputs, ns={"g": -1})
311
312 def test_explicit_global(self):
313 code = """
314 global g
315 x = g
316 g = 2
317 items = [g for g in [1]]
318 y = g
319 """
320 outputs = {"x": 1, "y": 2, "items": [1]}
321 self._check_in_scopes(code, outputs, ns={"g": 1})
322
323 def test_explicit_global_2(self):
324 code = """
325 global g
326 x = g
327 g = 2
328 items = [g for x in [1]]
329 y = g
330 """
331 outputs = {"x": 1, "y": 2, "items": [2]}
332 self._check_in_scopes(code, outputs, ns={"g": 1})
333
334 def test_explicit_global_3(self):
335 code = """
336 global g
337 fns = [lambda: g for g in [2]]
338 items = [fn() for fn in fns]
339 """
340 outputs = {"items": [2]}
341 self._check_in_scopes(code, outputs, ns={"g": 1})
342
343 def test_assignment_expression(self):
344 code = """
345 x = -1
346 items = [(x:=y) for y in range(3)]
347 """
348 outputs = {"x": 2}
349 # assignment expression in comprehension is disallowed in class scope
350 self._check_in_scopes(code, outputs, scopes=["module", "function"])
351
352 def test_free_var_in_comp_child(self):
353 code = """
354 lst = range(3)
355 funcs = [lambda: x for x in lst]
356 inc = [x + 1 for x in lst]
357 [x for x in inc]
358 x = funcs[0]()
359 """
360 outputs = {"x": 2}
361 self._check_in_scopes(code, outputs)
362
363 def test_shadow_with_free_and_local(self):
364 code = """
365 lst = range(3)
366 x = -1
367 funcs = [lambda: x for x in lst]
368 items = [x + 1 for x in lst]
369 """
370 outputs = {"x": -1}
371 self._check_in_scopes(code, outputs)
372
373 def test_shadow_comp_iterable_name(self):
374 code = """
375 x = [1]
376 y = [x for x in x]
377 """
378 outputs = {"x": [1]}
379 self._check_in_scopes(code, outputs)
380
381 def test_nested_free(self):
382 code = """
383 x = 1
384 def g():
385 [x for x in range(3)]
386 return x
387 g()
388 """
389 outputs = {"x": 1}
390 self._check_in_scopes(code, outputs, scopes=["module", "function"])
391
392 def test_introspecting_frame_locals(self):
393 code = """
394 import sys
395 [i for i in range(2)]
396 i = 20
397 sys._getframe().f_locals
398 """
399 outputs = {"i": 20}
400 self._check_in_scopes(code, outputs)
401
402 def test_nested(self):
403 code = """
404 l = [2, 3]
405 y = [[x ** 2 for x in range(x)] for x in l]
406 """
407 outputs = {"y": [[0, 1], [0, 1, 4]]}
408 self._check_in_scopes(code, outputs)
409
410 def test_nested_2(self):
411 code = """
412 l = [1, 2, 3]
413 x = 3
414 y = [x for [x ** x for x in range(x)][x - 1] in l]
415 """
416 outputs = {"y": [3, 3, 3]}
417 self._check_in_scopes(code, outputs, scopes=["module", "function"])
418 self._check_in_scopes(code, scopes=["class"], raises=NameError)
419
420 def test_nested_3(self):
421 code = """
422 l = [(1, 2), (3, 4), (5, 6)]
423 y = [x for (x, [x ** x for x in range(x)][x - 1]) in l]
424 """
425 outputs = {"y": [1, 3, 5]}
426 self._check_in_scopes(code, outputs)
427
428 def test_nested_4(self):
429 code = """
430 items = [([lambda: x for x in range(2)], lambda: x) for x in range(3)]
431 out = [([fn() for fn in fns], fn()) for fns, fn in items]
432 """
433 outputs = {"out": [([1, 1], 2), ([1, 1], 2), ([1, 1], 2)]}
434 self._check_in_scopes(code, outputs)
435
436 def test_nameerror(self):
437 code = """
438 [x for x in [1]]
439 x
440 """
441
442 self._check_in_scopes(code, raises=NameError)
443
444 def test_dunder_name(self):
445 code = """
446 y = [__x for __x in [1]]
447 """
448 outputs = {"y": [1]}
449 self._check_in_scopes(code, outputs)
450
451 def test_unbound_local_after_comprehension(self):
452 def f():
453 if False:
454 x = 0
455 [x for x in [1]]
456 return x
457
458 with self.assertRaises(UnboundLocalError):
459 f()
460
461 def test_unbound_local_inside_comprehension(self):
462 def f():
463 l = [None]
464 return [1 for (l[0], l) in [[1, 2]]]
465
466 with self.assertRaises(UnboundLocalError):
467 f()
468
469 def test_global_outside_cellvar_inside_plus_freevar(self):
470 code = """
471 a = 1
472 def f():
473 func, = [(lambda: b) for b in [a]]
474 return b, func()
475 x = f()
476 """
477 self._check_in_scopes(
478 code, {"x": (2, 1)}, ns={"b": 2}, scopes=["function", "module"])
479 # inside a class, the `a = 1` assignment is not visible
480 self._check_in_scopes(code, raises=NameError, scopes=["class"])
481
482 def test_cell_in_nested_comprehension(self):
483 code = """
484 a = 1
485 def f():
486 (func, inner_b), = [[lambda: b for b in c] + [b] for c in [[a]]]
487 return b, inner_b, func()
488 x = f()
489 """
490 self._check_in_scopes(
491 code, {"x": (2, 2, 1)}, ns={"b": 2}, scopes=["function", "module"])
492 # inside a class, the `a = 1` assignment is not visible
493 self._check_in_scopes(code, raises=NameError, scopes=["class"])
494
495 def test_name_error_in_class_scope(self):
496 code = """
497 y = 1
498 [x + y for x in range(2)]
499 """
500 self._check_in_scopes(code, raises=NameError, scopes=["class"])
501
502 def test_global_in_class_scope(self):
503 code = """
504 y = 2
505 vals = [(x, y) for x in range(2)]
506 """
507 outputs = {"vals": [(0, 1), (1, 1)]}
508 self._check_in_scopes(code, outputs, ns={"y": 1}, scopes=["class"])
509
510 def test_in_class_scope_inside_function_1(self):
511 code = """
512 class C:
513 y = 2
514 vals = [(x, y) for x in range(2)]
515 vals = C.vals
516 """
517 outputs = {"vals": [(0, 1), (1, 1)]}
518 self._check_in_scopes(code, outputs, ns={"y": 1}, scopes=["function"])
519
520 def test_in_class_scope_inside_function_2(self):
521 code = """
522 y = 1
523 class C:
524 y = 2
525 vals = [(x, y) for x in range(2)]
526 vals = C.vals
527 """
528 outputs = {"vals": [(0, 1), (1, 1)]}
529 self._check_in_scopes(code, outputs, scopes=["function"])
530
531 def test_in_class_scope_with_global(self):
532 code = """
533 y = 1
534 class C:
535 global y
536 y = 2
537 # Ensure the listcomp uses the global, not the value in the
538 # class namespace
539 locals()['y'] = 3
540 vals = [(x, y) for x in range(2)]
541 vals = C.vals
542 """
543 outputs = {"vals": [(0, 2), (1, 2)]}
544 self._check_in_scopes(code, outputs, scopes=["module", "class"])
545 outputs = {"vals": [(0, 1), (1, 1)]}
546 self._check_in_scopes(code, outputs, scopes=["function"])
547
548 def test_in_class_scope_with_nonlocal(self):
549 code = """
550 y = 1
551 class C:
552 nonlocal y
553 y = 2
554 # Ensure the listcomp uses the global, not the value in the
555 # class namespace
556 locals()['y'] = 3
557 vals = [(x, y) for x in range(2)]
558 vals = C.vals
559 """
560 outputs = {"vals": [(0, 2), (1, 2)]}
561 self._check_in_scopes(code, outputs, scopes=["function"])
562
563 def test_nested_has_free_var(self):
564 code = """
565 items = [a for a in [1] if [a for _ in [0]]]
566 """
567 outputs = {"items": [1]}
568 self._check_in_scopes(code, outputs, scopes=["class"])
569
570 def test_nested_free_var_not_bound_in_outer_comp(self):
571 code = """
572 z = 1
573 items = [a for a in [1] if [x for x in [1] if z]]
574 """
575 self._check_in_scopes(code, {"items": [1]}, scopes=["module", "function"])
576 self._check_in_scopes(code, {"items": []}, ns={"z": 0}, scopes=["class"])
577
578 def test_nested_free_var_in_iter(self):
579 code = """
580 items = [_C for _C in [1] for [0, 1][[x for x in [1] if _C][0]] in [2]]
581 """
582 self._check_in_scopes(code, {"items": [1]})
583
584 def test_nested_free_var_in_expr(self):
585 code = """
586 items = [(_C, [x for x in [1] if _C]) for _C in [0, 1]]
587 """
588 self._check_in_scopes(code, {"items": [(0, []), (1, [1])]})
589
590 def test_nested_listcomp_in_lambda(self):
591 code = """
592 f = [(z, lambda y: [(x, y, z) for x in [3]]) for z in [1]]
593 (z, func), = f
594 out = func(2)
595 """
596 self._check_in_scopes(code, {"z": 1, "out": [(3, 2, 1)]})
597
598 def test_lambda_in_iter(self):
599 code = """
600 (func, c), = [(a, b) for b in [1] for a in [lambda : a]]
601 d = func()
602 assert d is func
603 # must use "a" in this scope
604 e = a if False else None
605 """
606 self._check_in_scopes(code, {"c": 1, "e": None})
607
608 def test_assign_to_comp_iter_var_in_outer_function(self):
609 code = """
610 a = [1 for a in [0]]
611 """
612 self._check_in_scopes(code, {"a": [1]}, scopes=["function"])
613
614 def test_no_leakage_to_locals(self):
615 code = """
616 def b():
617 [a for b in [1] for _ in []]
618 return b, locals()
619 r, s = b()
620 x = r is b
621 y = list(s.keys())
622 """
623 self._check_in_scopes(code, {"x": True, "y": []}, scopes=["module"])
624 self._check_in_scopes(code, {"x": True, "y": ["b"]}, scopes=["function"])
625 self._check_in_scopes(code, raises=NameError, scopes=["class"])
626
627 def test_iter_var_available_in_locals(self):
628 code = """
629 l = [1, 2]
630 y = 0
631 items = [locals()["x"] for x in l]
632 items2 = [vars()["x"] for x in l]
633 items3 = [("x" in dir()) for x in l]
634 items4 = [eval("x") for x in l]
635 # x is available, and does not overwrite y
636 [exec("y = x") for x in l]
637 """
638 self._check_in_scopes(
639 code,
640 {
641 "items": [1, 2],
642 "items2": [1, 2],
643 "items3": [True, True],
644 "items4": [1, 2],
645 "y": 0
646 }
647 )
648
649 def test_comp_in_try_except(self):
650 template = """
651 value = ["ab"]
652 result = snapshot = None
653 try:
654 result = [{func}(value) for value in value]
655 except ValueError:
656 snapshot = value
657 raise
658 """
659 # No exception.
660 code = template.format(func='len')
661 self._check_in_scopes(code, {"value": ["ab"], "result": [2], "snapshot": None})
662 # Handles exception.
663 code = template.format(func='int')
664 self._check_in_scopes(code, {"value": ["ab"], "result": None, "snapshot": ["ab"]},
665 raises=ValueError)
666
667 def test_comp_in_try_finally(self):
668 template = """
669 value = ["ab"]
670 result = snapshot = None
671 try:
672 result = [{func}(value) for value in value]
673 finally:
674 snapshot = value
675 """
676 # No exception.
677 code = template.format(func='len')
678 self._check_in_scopes(code, {"value": ["ab"], "result": [2], "snapshot": ["ab"]})
679 # Handles exception.
680 code = template.format(func='int')
681 self._check_in_scopes(code, {"value": ["ab"], "result": None, "snapshot": ["ab"]},
682 raises=ValueError)
683
684 def test_exception_in_post_comp_call(self):
685 code = """
686 value = [1, None]
687 try:
688 [v for v in value].sort()
689 except TypeError:
690 pass
691 """
692 self._check_in_scopes(code, {"value": [1, None]})
693
694 def test_frame_locals(self):
695 code = """
696 val = "a" in [sys._getframe().f_locals for a in [0]][0]
697 """
698 import sys
699 self._check_in_scopes(code, {"val": False}, ns={"sys": sys})
700
701 code = """
702 val = [sys._getframe().f_locals["a"] for a in [0]][0]
703 """
704 self._check_in_scopes(code, {"val": 0}, ns={"sys": sys})
705
706 def _recursive_replace(self, maybe_code):
707 if not isinstance(maybe_code, types.CodeType):
708 return maybe_code
709 return maybe_code.replace(co_consts=tuple(
710 self._recursive_replace(c) for c in maybe_code.co_consts
711 ))
712
713 def _replacing_exec(self, code_string, ns):
714 co = compile(code_string, "<string>", "exec")
715 co = self._recursive_replace(co)
716 exec(co, ns)
717
718 def test_code_replace(self):
719 code = """
720 x = 3
721 [x for x in (1, 2)]
722 dir()
723 y = [x]
724 """
725 self._check_in_scopes(code, {"y": [3], "x": 3})
726 self._check_in_scopes(code, {"y": [3], "x": 3}, exec_func=self._replacing_exec)
727
728 def test_code_replace_extended_arg(self):
729 num_names = 300
730 assignments = "; ".join(f"x{i} = {i}" for i in range(num_names))
731 name_list = ", ".join(f"x{i}" for i in range(num_names))
732 expected = {
733 "y": list(range(num_names)),
734 **{f"x{i}": i for i in range(num_names)}
735 }
736 code = f"""
737 {assignments}
738 [({name_list}) for {name_list} in (range(300),)]
739 dir()
740 y = [{name_list}]
741 """
742 self._check_in_scopes(code, expected)
743 self._check_in_scopes(code, expected, exec_func=self._replacing_exec)
744
745 def test_multiple_comprehension_name_reuse(self):
746 code = """
747 [x for x in [1]]
748 y = [x for _ in [1]]
749 """
750 self._check_in_scopes(code, {"y": [3]}, ns={"x": 3})
751
752 code = """
753 x = 2
754 [x for x in [1]]
755 y = [x for _ in [1]]
756 """
757 self._check_in_scopes(code, {"x": 2, "y": [3]}, ns={"x": 3}, scopes=["class"])
758 self._check_in_scopes(code, {"x": 2, "y": [2]}, ns={"x": 3}, scopes=["function", "module"])
759
760 def test_exception_locations(self):
761 # The location of an exception raised from __init__ or
762 # __next__ should be the iterator expression
763
764 def init_raises():
765 try:
766 [x for x in BrokenIter(init_raises=True)]
767 except Exception as e:
768 return e
769
770 def next_raises():
771 try:
772 [x for x in BrokenIter(next_raises=True)]
773 except Exception as e:
774 return e
775
776 def iter_raises():
777 try:
778 [x for x in BrokenIter(iter_raises=True)]
779 except Exception as e:
780 return e
781
782 for func, expected in [(init_raises, "BrokenIter(init_raises=True)"),
783 (next_raises, "BrokenIter(next_raises=True)"),
784 (iter_raises, "BrokenIter(iter_raises=True)"),
785 ]:
786 with self.subTest(func):
787 exc = func()
788 f = traceback.extract_tb(exc.__traceback__)[0]
789 indent = 16
790 co = func.__code__
791 self.assertEqual(f.lineno, co.co_firstlineno + 2)
792 self.assertEqual(f.end_lineno, co.co_firstlineno + 2)
793 self.assertEqual(f.line[f.colno - indent : f.end_colno - indent],
794 expected)
795
796 def test_only_calls_dunder_iter_once(self):
797
798 class Iterator:
799
800 def __init__(self):
801 self.val = 0
802
803 def __next__(self):
804 if self.val == 2:
805 raise StopIteration
806 self.val += 1
807 return self.val
808
809 # No __iter__ method
810
811 class C:
812
813 def __iter__(self):
814 return Iterator()
815
816 self.assertEqual([1, 2], [i for i in C()])
817
818 __test__ = {'doctests' : doctests}
819
820 def load_tests(loader, tests, pattern):
821 tests.addTest(doctest.DocTestSuite())
822 return tests
823
824
825 if __name__ == "__main__":
826 unittest.main()