| 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___defined(self): |
| 175 |
code = """ |
| 176 |
__class__ = 2 |
| 177 |
res = [__class__ for x in [1]] |
| 178 |
""" |
| 179 |
self._check_in_scopes( |
| 180 |
code, outputs={"res": [2]}, scopes=["module", "function"]) |
| 181 |
self._check_in_scopes(code, raises=NameError, scopes=["class"]) |
| 182 |
|
| 183 |
def test_references___classdict__(self): |
| 184 |
code = """ |
| 185 |
class i: [__classdict__ for x in y] |
| 186 |
""" |
| 187 |
self._check_in_scopes(code, raises=NameError) |
| 188 |
|
| 189 |
def test_references___conditional_annotations__(self): |
| 190 |
code = """ |
| 191 |
class i: [__conditional_annotations__ for x in y] |
| 192 |
""" |
| 193 |
self._check_in_scopes(code, raises=NameError) |
| 194 |
|
| 195 |
def test_references___class___enclosing(self): |
| 196 |
code = """ |
| 197 |
__class__ = 2 |
| 198 |
class C: |
| 199 |
res = [__class__ for x in [1]] |
| 200 |
res = C.res |
| 201 |
""" |
| 202 |
self._check_in_scopes(code, raises=NameError) |
| 203 |
|
| 204 |
def test_super_and_class_cell_in_sibling_comps(self): |
| 205 |
code = """ |
| 206 |
[super for _ in [1]] |
| 207 |
[__class__ for _ in [1]] |
| 208 |
""" |
| 209 |
self._check_in_scopes(code, raises=NameError) |
| 210 |
|
| 211 |
def test_inner_cell_shadows_outer(self): |
| 212 |
code = """ |
| 213 |
items = [(lambda: i) for i in range(5)] |
| 214 |
i = 20 |
| 215 |
y = [x() for x in items] |
| 216 |
""" |
| 217 |
outputs = {"y": [4, 4, 4, 4, 4], "i": 20} |
| 218 |
self._check_in_scopes(code, outputs) |
| 219 |
|
| 220 |
def test_inner_cell_shadows_outer_no_store(self): |
| 221 |
code = """ |
| 222 |
def f(x): |
| 223 |
return [lambda: x for x in range(x)], x |
| 224 |
fns, x = f(2) |
| 225 |
y = [fn() for fn in fns] |
| 226 |
""" |
| 227 |
outputs = {"y": [1, 1], "x": 2} |
| 228 |
self._check_in_scopes(code, outputs) |
| 229 |
|
| 230 |
def test_closure_can_jump_over_comp_scope(self): |
| 231 |
code = """ |
| 232 |
items = [(lambda: y) for i in range(5)] |
| 233 |
y = 2 |
| 234 |
z = [x() for x in items] |
| 235 |
""" |
| 236 |
outputs = {"z": [2, 2, 2, 2, 2]} |
| 237 |
self._check_in_scopes(code, outputs, scopes=["module", "function"]) |
| 238 |
|
| 239 |
def test_cell_inner_free_outer(self): |
| 240 |
code = """ |
| 241 |
def f(): |
| 242 |
return [lambda: x for x in (x, [1])[1]] |
| 243 |
x = ... |
| 244 |
y = [fn() for fn in f()] |
| 245 |
""" |
| 246 |
outputs = {"y": [1]} |
| 247 |
self._check_in_scopes(code, outputs, scopes=["module", "function"]) |
| 248 |
|
| 249 |
def test_free_inner_cell_outer(self): |
| 250 |
code = """ |
| 251 |
g = 2 |
| 252 |
def f(): |
| 253 |
return g |
| 254 |
y = [g for x in [1]] |
| 255 |
""" |
| 256 |
outputs = {"y": [2]} |
| 257 |
self._check_in_scopes(code, outputs, scopes=["module", "function"]) |
| 258 |
self._check_in_scopes(code, scopes=["class"], raises=NameError) |
| 259 |
|
| 260 |
def test_inner_cell_shadows_outer_redefined(self): |
| 261 |
code = """ |
| 262 |
y = 10 |
| 263 |
items = [(lambda: y) for y in range(5)] |
| 264 |
x = y |
| 265 |
y = 20 |
| 266 |
out = [z() for z in items] |
| 267 |
""" |
| 268 |
outputs = {"x": 10, "out": [4, 4, 4, 4, 4]} |
| 269 |
self._check_in_scopes(code, outputs) |
| 270 |
|
| 271 |
def test_shadows_outer_cell(self): |
| 272 |
code = """ |
| 273 |
def inner(): |
| 274 |
return g |
| 275 |
[g for g in range(5)] |
| 276 |
x = inner() |
| 277 |
""" |
| 278 |
outputs = {"x": -1} |
| 279 |
self._check_in_scopes(code, outputs, ns={"g": -1}) |
| 280 |
|
| 281 |
def test_explicit_global(self): |
| 282 |
code = """ |
| 283 |
global g |
| 284 |
x = g |
| 285 |
g = 2 |
| 286 |
items = [g for g in [1]] |
| 287 |
y = g |
| 288 |
""" |
| 289 |
outputs = {"x": 1, "y": 2, "items": [1]} |
| 290 |
self._check_in_scopes(code, outputs, ns={"g": 1}) |
| 291 |
|
| 292 |
def test_explicit_global_2(self): |
| 293 |
code = """ |
| 294 |
global g |
| 295 |
x = g |
| 296 |
g = 2 |
| 297 |
items = [g for x in [1]] |
| 298 |
y = g |
| 299 |
""" |
| 300 |
outputs = {"x": 1, "y": 2, "items": [2]} |
| 301 |
self._check_in_scopes(code, outputs, ns={"g": 1}) |
| 302 |
|
| 303 |
def test_explicit_global_3(self): |
| 304 |
code = """ |
| 305 |
global g |
| 306 |
fns = [lambda: g for g in [2]] |
| 307 |
items = [fn() for fn in fns] |
| 308 |
""" |
| 309 |
outputs = {"items": [2]} |
| 310 |
self._check_in_scopes(code, outputs, ns={"g": 1}) |
| 311 |
|
| 312 |
def test_assignment_expression(self): |
| 313 |
code = """ |
| 314 |
x = -1 |
| 315 |
items = [(x:=y) for y in range(3)] |
| 316 |
""" |
| 317 |
outputs = {"x": 2} |
| 318 |
# assignment expression in comprehension is disallowed in class scope |
| 319 |
self._check_in_scopes(code, outputs, scopes=["module", "function"]) |
| 320 |
|
| 321 |
def test_free_var_in_comp_child(self): |
| 322 |
code = """ |
| 323 |
lst = range(3) |
| 324 |
funcs = [lambda: x for x in lst] |
| 325 |
inc = [x + 1 for x in lst] |
| 326 |
[x for x in inc] |
| 327 |
x = funcs[0]() |
| 328 |
""" |
| 329 |
outputs = {"x": 2} |
| 330 |
self._check_in_scopes(code, outputs) |
| 331 |
|
| 332 |
def test_shadow_with_free_and_local(self): |
| 333 |
code = """ |
| 334 |
lst = range(3) |
| 335 |
x = -1 |
| 336 |
funcs = [lambda: x for x in lst] |
| 337 |
items = [x + 1 for x in lst] |
| 338 |
""" |
| 339 |
outputs = {"x": -1} |
| 340 |
self._check_in_scopes(code, outputs) |
| 341 |
|
| 342 |
def test_shadow_comp_iterable_name(self): |
| 343 |
code = """ |
| 344 |
x = [1] |
| 345 |
y = [x for x in x] |
| 346 |
""" |
| 347 |
outputs = {"x": [1]} |
| 348 |
self._check_in_scopes(code, outputs) |
| 349 |
|
| 350 |
def test_nested_free(self): |
| 351 |
code = """ |
| 352 |
x = 1 |
| 353 |
def g(): |
| 354 |
[x for x in range(3)] |
| 355 |
return x |
| 356 |
g() |
| 357 |
""" |
| 358 |
outputs = {"x": 1} |
| 359 |
self._check_in_scopes(code, outputs, scopes=["module", "function"]) |
| 360 |
|
| 361 |
def test_introspecting_frame_locals(self): |
| 362 |
code = """ |
| 363 |
import sys |
| 364 |
[i for i in range(2)] |
| 365 |
i = 20 |
| 366 |
sys._getframe().f_locals |
| 367 |
""" |
| 368 |
outputs = {"i": 20} |
| 369 |
self._check_in_scopes(code, outputs) |
| 370 |
|
| 371 |
def test_nested(self): |
| 372 |
code = """ |
| 373 |
l = [2, 3] |
| 374 |
y = [[x ** 2 for x in range(x)] for x in l] |
| 375 |
""" |
| 376 |
outputs = {"y": [[0, 1], [0, 1, 4]]} |
| 377 |
self._check_in_scopes(code, outputs) |
| 378 |
|
| 379 |
def test_nested_2(self): |
| 380 |
code = """ |
| 381 |
l = [1, 2, 3] |
| 382 |
x = 3 |
| 383 |
y = [x for [x ** x for x in range(x)][x - 1] in l] |
| 384 |
""" |
| 385 |
outputs = {"y": [3, 3, 3]} |
| 386 |
self._check_in_scopes(code, outputs, scopes=["module", "function"]) |
| 387 |
self._check_in_scopes(code, scopes=["class"], raises=NameError) |
| 388 |
|
| 389 |
def test_nested_3(self): |
| 390 |
code = """ |
| 391 |
l = [(1, 2), (3, 4), (5, 6)] |
| 392 |
y = [x for (x, [x ** x for x in range(x)][x - 1]) in l] |
| 393 |
""" |
| 394 |
outputs = {"y": [1, 3, 5]} |
| 395 |
self._check_in_scopes(code, outputs) |
| 396 |
|
| 397 |
def test_nested_4(self): |
| 398 |
code = """ |
| 399 |
items = [([lambda: x for x in range(2)], lambda: x) for x in range(3)] |
| 400 |
out = [([fn() for fn in fns], fn()) for fns, fn in items] |
| 401 |
""" |
| 402 |
outputs = {"out": [([1, 1], 2), ([1, 1], 2), ([1, 1], 2)]} |
| 403 |
self._check_in_scopes(code, outputs) |
| 404 |
|
| 405 |
def test_nameerror(self): |
| 406 |
code = """ |
| 407 |
[x for x in [1]] |
| 408 |
x |
| 409 |
""" |
| 410 |
|
| 411 |
self._check_in_scopes(code, raises=NameError) |
| 412 |
|
| 413 |
def test_dunder_name(self): |
| 414 |
code = """ |
| 415 |
y = [__x for __x in [1]] |
| 416 |
""" |
| 417 |
outputs = {"y": [1]} |
| 418 |
self._check_in_scopes(code, outputs) |
| 419 |
|
| 420 |
def test_unbound_local_after_comprehension(self): |
| 421 |
def f(): |
| 422 |
if False: |
| 423 |
x = 0 |
| 424 |
[x for x in [1]] |
| 425 |
return x |
| 426 |
|
| 427 |
with self.assertRaises(UnboundLocalError): |
| 428 |
f() |
| 429 |
|
| 430 |
def test_unbound_local_inside_comprehension(self): |
| 431 |
def f(): |
| 432 |
l = [None] |
| 433 |
return [1 for (l[0], l) in [[1, 2]]] |
| 434 |
|
| 435 |
with self.assertRaises(UnboundLocalError): |
| 436 |
f() |
| 437 |
|
| 438 |
def test_global_outside_cellvar_inside_plus_freevar(self): |
| 439 |
code = """ |
| 440 |
a = 1 |
| 441 |
def f(): |
| 442 |
func, = [(lambda: b) for b in [a]] |
| 443 |
return b, func() |
| 444 |
x = f() |
| 445 |
""" |
| 446 |
self._check_in_scopes( |
| 447 |
code, {"x": (2, 1)}, ns={"b": 2}, scopes=["function", "module"]) |
| 448 |
# inside a class, the `a = 1` assignment is not visible |
| 449 |
self._check_in_scopes(code, raises=NameError, scopes=["class"]) |
| 450 |
|
| 451 |
def test_cell_in_nested_comprehension(self): |
| 452 |
code = """ |
| 453 |
a = 1 |
| 454 |
def f(): |
| 455 |
(func, inner_b), = [[lambda: b for b in c] + [b] for c in [[a]]] |
| 456 |
return b, inner_b, func() |
| 457 |
x = f() |
| 458 |
""" |
| 459 |
self._check_in_scopes( |
| 460 |
code, {"x": (2, 2, 1)}, ns={"b": 2}, scopes=["function", "module"]) |
| 461 |
# inside a class, the `a = 1` assignment is not visible |
| 462 |
self._check_in_scopes(code, raises=NameError, scopes=["class"]) |
| 463 |
|
| 464 |
def test_name_error_in_class_scope(self): |
| 465 |
code = """ |
| 466 |
y = 1 |
| 467 |
[x + y for x in range(2)] |
| 468 |
""" |
| 469 |
self._check_in_scopes(code, raises=NameError, scopes=["class"]) |
| 470 |
|
| 471 |
def test_global_in_class_scope(self): |
| 472 |
code = """ |
| 473 |
y = 2 |
| 474 |
vals = [(x, y) for x in range(2)] |
| 475 |
""" |
| 476 |
outputs = {"vals": [(0, 1), (1, 1)]} |
| 477 |
self._check_in_scopes(code, outputs, ns={"y": 1}, scopes=["class"]) |
| 478 |
|
| 479 |
def test_in_class_scope_inside_function_1(self): |
| 480 |
code = """ |
| 481 |
class C: |
| 482 |
y = 2 |
| 483 |
vals = [(x, y) for x in range(2)] |
| 484 |
vals = C.vals |
| 485 |
""" |
| 486 |
outputs = {"vals": [(0, 1), (1, 1)]} |
| 487 |
self._check_in_scopes(code, outputs, ns={"y": 1}, scopes=["function"]) |
| 488 |
|
| 489 |
def test_in_class_scope_inside_function_2(self): |
| 490 |
code = """ |
| 491 |
y = 1 |
| 492 |
class C: |
| 493 |
y = 2 |
| 494 |
vals = [(x, y) for x in range(2)] |
| 495 |
vals = C.vals |
| 496 |
""" |
| 497 |
outputs = {"vals": [(0, 1), (1, 1)]} |
| 498 |
self._check_in_scopes(code, outputs, scopes=["function"]) |
| 499 |
|
| 500 |
def test_in_class_scope_with_global(self): |
| 501 |
code = """ |
| 502 |
y = 1 |
| 503 |
class C: |
| 504 |
global y |
| 505 |
y = 2 |
| 506 |
# Ensure the listcomp uses the global, not the value in the |
| 507 |
# class namespace |
| 508 |
locals()['y'] = 3 |
| 509 |
vals = [(x, y) for x in range(2)] |
| 510 |
vals = C.vals |
| 511 |
""" |
| 512 |
outputs = {"vals": [(0, 2), (1, 2)]} |
| 513 |
self._check_in_scopes(code, outputs, scopes=["module", "class"]) |
| 514 |
outputs = {"vals": [(0, 1), (1, 1)]} |
| 515 |
self._check_in_scopes(code, outputs, scopes=["function"]) |
| 516 |
|
| 517 |
def test_in_class_scope_with_nonlocal(self): |
| 518 |
code = """ |
| 519 |
y = 1 |
| 520 |
class C: |
| 521 |
nonlocal y |
| 522 |
y = 2 |
| 523 |
# Ensure the listcomp uses the global, not the value in the |
| 524 |
# class namespace |
| 525 |
locals()['y'] = 3 |
| 526 |
vals = [(x, y) for x in range(2)] |
| 527 |
vals = C.vals |
| 528 |
""" |
| 529 |
outputs = {"vals": [(0, 2), (1, 2)]} |
| 530 |
self._check_in_scopes(code, outputs, scopes=["function"]) |
| 531 |
|
| 532 |
def test_nested_has_free_var(self): |
| 533 |
code = """ |
| 534 |
items = [a for a in [1] if [a for _ in [0]]] |
| 535 |
""" |
| 536 |
outputs = {"items": [1]} |
| 537 |
self._check_in_scopes(code, outputs, scopes=["class"]) |
| 538 |
|
| 539 |
def test_nested_free_var_not_bound_in_outer_comp(self): |
| 540 |
code = """ |
| 541 |
z = 1 |
| 542 |
items = [a for a in [1] if [x for x in [1] if z]] |
| 543 |
""" |
| 544 |
self._check_in_scopes(code, {"items": [1]}, scopes=["module", "function"]) |
| 545 |
self._check_in_scopes(code, {"items": []}, ns={"z": 0}, scopes=["class"]) |
| 546 |
|
| 547 |
def test_nested_free_var_in_iter(self): |
| 548 |
code = """ |
| 549 |
items = [_C for _C in [1] for [0, 1][[x for x in [1] if _C][0]] in [2]] |
| 550 |
""" |
| 551 |
self._check_in_scopes(code, {"items": [1]}) |
| 552 |
|
| 553 |
def test_nested_free_var_in_expr(self): |
| 554 |
code = """ |
| 555 |
items = [(_C, [x for x in [1] if _C]) for _C in [0, 1]] |
| 556 |
""" |
| 557 |
self._check_in_scopes(code, {"items": [(0, []), (1, [1])]}) |
| 558 |
|
| 559 |
def test_nested_listcomp_in_lambda(self): |
| 560 |
code = """ |
| 561 |
f = [(z, lambda y: [(x, y, z) for x in [3]]) for z in [1]] |
| 562 |
(z, func), = f |
| 563 |
out = func(2) |
| 564 |
""" |
| 565 |
self._check_in_scopes(code, {"z": 1, "out": [(3, 2, 1)]}) |
| 566 |
|
| 567 |
def test_lambda_in_iter(self): |
| 568 |
code = """ |
| 569 |
(func, c), = [(a, b) for b in [1] for a in [lambda : a]] |
| 570 |
d = func() |
| 571 |
assert d is func |
| 572 |
# must use "a" in this scope |
| 573 |
e = a if False else None |
| 574 |
""" |
| 575 |
self._check_in_scopes(code, {"c": 1, "e": None}) |
| 576 |
|
| 577 |
def test_assign_to_comp_iter_var_in_outer_function(self): |
| 578 |
code = """ |
| 579 |
a = [1 for a in [0]] |
| 580 |
""" |
| 581 |
self._check_in_scopes(code, {"a": [1]}, scopes=["function"]) |
| 582 |
|
| 583 |
def test_no_leakage_to_locals(self): |
| 584 |
code = """ |
| 585 |
def b(): |
| 586 |
[a for b in [1] for _ in []] |
| 587 |
return b, locals() |
| 588 |
r, s = b() |
| 589 |
x = r is b |
| 590 |
y = list(s.keys()) |
| 591 |
""" |
| 592 |
self._check_in_scopes(code, {"x": True, "y": []}, scopes=["module"]) |
| 593 |
self._check_in_scopes(code, {"x": True, "y": ["b"]}, scopes=["function"]) |
| 594 |
self._check_in_scopes(code, raises=NameError, scopes=["class"]) |
| 595 |
|
| 596 |
def test_iter_var_available_in_locals(self): |
| 597 |
code = """ |
| 598 |
l = [1, 2] |
| 599 |
y = 0 |
| 600 |
items = [locals()["x"] for x in l] |
| 601 |
items2 = [vars()["x"] for x in l] |
| 602 |
items3 = [("x" in dir()) for x in l] |
| 603 |
items4 = [eval("x") for x in l] |
| 604 |
# x is available, and does not overwrite y |
| 605 |
[exec("y = x") for x in l] |
| 606 |
""" |
| 607 |
self._check_in_scopes( |
| 608 |
code, |
| 609 |
{ |
| 610 |
"items": [1, 2], |
| 611 |
"items2": [1, 2], |
| 612 |
"items3": [True, True], |
| 613 |
"items4": [1, 2], |
| 614 |
"y": 0 |
| 615 |
} |
| 616 |
) |
| 617 |
|
| 618 |
def test_comp_in_try_except(self): |
| 619 |
template = """ |
| 620 |
value = ["ab"] |
| 621 |
result = snapshot = None |
| 622 |
try: |
| 623 |
result = [{func}(value) for value in value] |
| 624 |
except ValueError: |
| 625 |
snapshot = value |
| 626 |
raise |
| 627 |
""" |
| 628 |
# No exception. |
| 629 |
code = template.format(func='len') |
| 630 |
self._check_in_scopes(code, {"value": ["ab"], "result": [2], "snapshot": None}) |
| 631 |
# Handles exception. |
| 632 |
code = template.format(func='int') |
| 633 |
self._check_in_scopes(code, {"value": ["ab"], "result": None, "snapshot": ["ab"]}, |
| 634 |
raises=ValueError) |
| 635 |
|
| 636 |
def test_comp_in_try_finally(self): |
| 637 |
template = """ |
| 638 |
value = ["ab"] |
| 639 |
result = snapshot = None |
| 640 |
try: |
| 641 |
result = [{func}(value) for value in value] |
| 642 |
finally: |
| 643 |
snapshot = value |
| 644 |
""" |
| 645 |
# No exception. |
| 646 |
code = template.format(func='len') |
| 647 |
self._check_in_scopes(code, {"value": ["ab"], "result": [2], "snapshot": ["ab"]}) |
| 648 |
# Handles exception. |
| 649 |
code = template.format(func='int') |
| 650 |
self._check_in_scopes(code, {"value": ["ab"], "result": None, "snapshot": ["ab"]}, |
| 651 |
raises=ValueError) |
| 652 |
|
| 653 |
def test_exception_in_post_comp_call(self): |
| 654 |
code = """ |
| 655 |
value = [1, None] |
| 656 |
try: |
| 657 |
[v for v in value].sort() |
| 658 |
except TypeError: |
| 659 |
pass |
| 660 |
""" |
| 661 |
self._check_in_scopes(code, {"value": [1, None]}) |
| 662 |
|
| 663 |
def test_frame_locals(self): |
| 664 |
code = """ |
| 665 |
val = "a" in [sys._getframe().f_locals for a in [0]][0] |
| 666 |
""" |
| 667 |
import sys |
| 668 |
self._check_in_scopes(code, {"val": False}, ns={"sys": sys}) |
| 669 |
|
| 670 |
code = """ |
| 671 |
val = [sys._getframe().f_locals["a"] for a in [0]][0] |
| 672 |
""" |
| 673 |
self._check_in_scopes(code, {"val": 0}, ns={"sys": sys}) |
| 674 |
|
| 675 |
def _recursive_replace(self, maybe_code): |
| 676 |
if not isinstance(maybe_code, types.CodeType): |
| 677 |
return maybe_code |
| 678 |
return maybe_code.replace(co_consts=tuple( |
| 679 |
self._recursive_replace(c) for c in maybe_code.co_consts |
| 680 |
)) |
| 681 |
|
| 682 |
def _replacing_exec(self, code_string, ns): |
| 683 |
co = compile(code_string, "<string>", "exec") |
| 684 |
co = self._recursive_replace(co) |
| 685 |
exec(co, ns) |
| 686 |
|
| 687 |
def test_code_replace(self): |
| 688 |
code = """ |
| 689 |
x = 3 |
| 690 |
[x for x in (1, 2)] |
| 691 |
dir() |
| 692 |
y = [x] |
| 693 |
""" |
| 694 |
self._check_in_scopes(code, {"y": [3], "x": 3}) |
| 695 |
self._check_in_scopes(code, {"y": [3], "x": 3}, exec_func=self._replacing_exec) |
| 696 |
|
| 697 |
def test_code_replace_extended_arg(self): |
| 698 |
num_names = 300 |
| 699 |
assignments = "; ".join(f"x{i} = {i}" for i in range(num_names)) |
| 700 |
name_list = ", ".join(f"x{i}" for i in range(num_names)) |
| 701 |
expected = { |
| 702 |
"y": list(range(num_names)), |
| 703 |
**{f"x{i}": i for i in range(num_names)} |
| 704 |
} |
| 705 |
code = f""" |
| 706 |
{assignments} |
| 707 |
[({name_list}) for {name_list} in (range(300),)] |
| 708 |
dir() |
| 709 |
y = [{name_list}] |
| 710 |
""" |
| 711 |
self._check_in_scopes(code, expected) |
| 712 |
self._check_in_scopes(code, expected, exec_func=self._replacing_exec) |
| 713 |
|
| 714 |
def test_multiple_comprehension_name_reuse(self): |
| 715 |
code = """ |
| 716 |
[x for x in [1]] |
| 717 |
y = [x for _ in [1]] |
| 718 |
""" |
| 719 |
self._check_in_scopes(code, {"y": [3]}, ns={"x": 3}) |
| 720 |
|
| 721 |
code = """ |
| 722 |
x = 2 |
| 723 |
[x for x in [1]] |
| 724 |
y = [x for _ in [1]] |
| 725 |
""" |
| 726 |
self._check_in_scopes(code, {"x": 2, "y": [3]}, ns={"x": 3}, scopes=["class"]) |
| 727 |
self._check_in_scopes(code, {"x": 2, "y": [2]}, ns={"x": 3}, scopes=["function", "module"]) |
| 728 |
|
| 729 |
def test_exception_locations(self): |
| 730 |
# The location of an exception raised from __init__ or |
| 731 |
# __next__ should be the iterator expression |
| 732 |
|
| 733 |
def init_raises(): |
| 734 |
try: |
| 735 |
[x for x in BrokenIter(init_raises=True)] |
| 736 |
except Exception as e: |
| 737 |
return e |
| 738 |
|
| 739 |
def next_raises(): |
| 740 |
try: |
| 741 |
[x for x in BrokenIter(next_raises=True)] |
| 742 |
except Exception as e: |
| 743 |
return e |
| 744 |
|
| 745 |
def iter_raises(): |
| 746 |
try: |
| 747 |
[x for x in BrokenIter(iter_raises=True)] |
| 748 |
except Exception as e: |
| 749 |
return e |
| 750 |
|
| 751 |
for func, expected in [(init_raises, "BrokenIter(init_raises=True)"), |
| 752 |
(next_raises, "BrokenIter(next_raises=True)"), |
| 753 |
(iter_raises, "BrokenIter(iter_raises=True)"), |
| 754 |
]: |
| 755 |
with self.subTest(func): |
| 756 |
exc = func() |
| 757 |
f = traceback.extract_tb(exc.__traceback__)[0] |
| 758 |
indent = 16 |
| 759 |
co = func.__code__ |
| 760 |
self.assertEqual(f.lineno, co.co_firstlineno + 2) |
| 761 |
self.assertEqual(f.end_lineno, co.co_firstlineno + 2) |
| 762 |
self.assertEqual(f.line[f.colno - indent : f.end_colno - indent], |
| 763 |
expected) |
| 764 |
|
| 765 |
def test_only_calls_dunder_iter_once(self): |
| 766 |
|
| 767 |
class Iterator: |
| 768 |
|
| 769 |
def __init__(self): |
| 770 |
self.val = 0 |
| 771 |
|
| 772 |
def __next__(self): |
| 773 |
if self.val == 2: |
| 774 |
raise StopIteration |
| 775 |
self.val += 1 |
| 776 |
return self.val |
| 777 |
|
| 778 |
# No __iter__ method |
| 779 |
|
| 780 |
class C: |
| 781 |
|
| 782 |
def __iter__(self): |
| 783 |
return Iterator() |
| 784 |
|
| 785 |
self.assertEqual([1, 2], [i for i in C()]) |
| 786 |
|
| 787 |
__test__ = {'doctests' : doctests} |
| 788 |
|
| 789 |
def load_tests(loader, tests, pattern): |
| 790 |
tests.addTest(doctest.DocTestSuite()) |
| 791 |
return tests |
| 792 |
|
| 793 |
|
| 794 |
if __name__ == "__main__": |
| 795 |
unittest.main() |