|
1 | 1 | import gc |
2 | 2 | import sys |
3 | 3 | import unittest |
| 4 | +import warnings |
4 | 5 | import weakref |
5 | 6 |
|
6 | 7 | from test import support |
@@ -217,6 +218,46 @@ def gen(): |
217 | 218 | self.assertEqual(next(g), "done") |
218 | 219 | self.assertEqual(sys.exc_info(), (None, None, None)) |
219 | 220 |
|
| 221 | + def test_stopiteration_warning(self): |
| 222 | + # See also PEP 479. |
| 223 | + |
| 224 | + def gen(): |
| 225 | + raise StopIteration |
| 226 | + yield |
| 227 | + |
| 228 | + with self.assertRaises(StopIteration), \ |
| 229 | + self.assertWarnsRegex(PendingDeprecationWarning, "StopIteration"): |
| 230 | + |
| 231 | + next(gen()) |
| 232 | + |
| 233 | + with self.assertRaisesRegex(PendingDeprecationWarning, |
| 234 | + "generator .* raised StopIteration"), \ |
| 235 | + warnings.catch_warnings(): |
| 236 | + |
| 237 | + warnings.simplefilter('error') |
| 238 | + next(gen()) |
| 239 | + |
| 240 | + |
| 241 | + def test_tutorial_stopiteration(self): |
| 242 | + # Raise StopIteration" stops the generator too: |
| 243 | + |
| 244 | + def f(): |
| 245 | + yield 1 |
| 246 | + raise StopIteration |
| 247 | + yield 2 # never reached |
| 248 | + |
| 249 | + g = f() |
| 250 | + self.assertEqual(next(g), 1) |
| 251 | + |
| 252 | + with self.assertWarnsRegex(PendingDeprecationWarning, "StopIteration"): |
| 253 | + with self.assertRaises(StopIteration): |
| 254 | + next(g) |
| 255 | + |
| 256 | + with self.assertRaises(StopIteration): |
| 257 | + # This time StopIteration isn't raised from the generator's body, |
| 258 | + # hence no warning. |
| 259 | + next(g) |
| 260 | + |
220 | 261 |
|
221 | 262 | tutorial_tests = """ |
222 | 263 | Let's try a simple generator: |
@@ -263,26 +304,7 @@ def gen(): |
263 | 304 | File "<stdin>", line 1, in ? |
264 | 305 | StopIteration |
265 | 306 |
|
266 | | -"raise StopIteration" stops the generator too: |
267 | | -
|
268 | | - >>> def f(): |
269 | | - ... yield 1 |
270 | | - ... raise StopIteration |
271 | | - ... yield 2 # never reached |
272 | | - ... |
273 | | - >>> g = f() |
274 | | - >>> next(g) |
275 | | - 1 |
276 | | - >>> next(g) |
277 | | - Traceback (most recent call last): |
278 | | - File "<stdin>", line 1, in ? |
279 | | - StopIteration |
280 | | - >>> next(g) |
281 | | - Traceback (most recent call last): |
282 | | - File "<stdin>", line 1, in ? |
283 | | - StopIteration |
284 | | -
|
285 | | -However, they are not exactly equivalent: |
| 307 | +However, "return" and StopIteration are not exactly equivalent: |
286 | 308 |
|
287 | 309 | >>> def g1(): |
288 | 310 | ... try: |
|
0 commit comments