test_scope.py 19.7 KB
Newer Older
1
import unittest
2 3
import weakref

4
from test.support import check_syntax_error, cpython_only
Jeremy Hylton's avatar
Jeremy Hylton committed
5

6

7
class ScopeTests(unittest.TestCase):
Jeremy Hylton's avatar
Jeremy Hylton committed
8

9
    def testSimpleNesting(self):
Jeremy Hylton's avatar
Jeremy Hylton committed
10

11 12 13 14
        def make_adder(x):
            def adder(y):
                return x + y
            return adder
Jeremy Hylton's avatar
Jeremy Hylton committed
15

16 17
        inc = make_adder(1)
        plus10 = make_adder(10)
Jeremy Hylton's avatar
Jeremy Hylton committed
18

19 20
        self.assertEqual(inc(1), 2)
        self.assertEqual(plus10(-2), 8)
Jeremy Hylton's avatar
Jeremy Hylton committed
21

22
    def testExtraNesting(self):
Jeremy Hylton's avatar
Jeremy Hylton committed
23

24 25 26 27 28 29
        def make_adder2(x):
            def extra(): # check freevars passing through non-use scopes
                def adder(y):
                    return x + y
                return adder
            return extra()
Jeremy Hylton's avatar
Jeremy Hylton committed
30

31 32
        inc = make_adder2(1)
        plus10 = make_adder2(10)
Jeremy Hylton's avatar
Jeremy Hylton committed
33

34 35
        self.assertEqual(inc(1), 2)
        self.assertEqual(plus10(-2), 8)
Jeremy Hylton's avatar
Jeremy Hylton committed
36

37
    def testSimpleAndRebinding(self):
Jeremy Hylton's avatar
Jeremy Hylton committed
38

39 40 41 42 43
        def make_adder3(x):
            def adder(y):
                return x + y
            x = x + 1 # check tracking of assignment to x in defining scope
            return adder
Jeremy Hylton's avatar
Jeremy Hylton committed
44

45 46
        inc = make_adder3(0)
        plus10 = make_adder3(9)
Jeremy Hylton's avatar
Jeremy Hylton committed
47

48 49
        self.assertEqual(inc(1), 2)
        self.assertEqual(plus10(-2), 8)
Jeremy Hylton's avatar
Jeremy Hylton committed
50

51
    def testNestingGlobalNoFree(self):
Jeremy Hylton's avatar
Jeremy Hylton committed
52

53 54 55 56 57 58 59 60
        def make_adder4(): # XXX add exta level of indirection
            def nest():
                def nest():
                    def adder(y):
                        return global_x + y # check that plain old globals work
                    return adder
                return nest()
            return nest()
Jeremy Hylton's avatar
Jeremy Hylton committed
61

62 63 64
        global_x = 1
        adder = make_adder4()
        self.assertEqual(adder(1), 2)
Jeremy Hylton's avatar
Jeremy Hylton committed
65

66 67
        global_x = 10
        self.assertEqual(adder(-2), 8)
Jeremy Hylton's avatar
Jeremy Hylton committed
68

69
    def testNestingThroughClass(self):
Jeremy Hylton's avatar
Jeremy Hylton committed
70

71 72 73 74 75
        def make_adder5(x):
            class Adder:
                def __call__(self, y):
                    return x + y
            return Adder()
Jeremy Hylton's avatar
Jeremy Hylton committed
76

77 78
        inc = make_adder5(1)
        plus10 = make_adder5(10)
Jeremy Hylton's avatar
Jeremy Hylton committed
79

80 81
        self.assertEqual(inc(1), 2)
        self.assertEqual(plus10(-2), 8)
Jeremy Hylton's avatar
Jeremy Hylton committed
82

83
    def testNestingPlusFreeRefToGlobal(self):
Jeremy Hylton's avatar
Jeremy Hylton committed
84

85 86 87 88 89 90
        def make_adder6(x):
            global global_nest_x
            def adder(y):
                return global_nest_x + y
            global_nest_x = x
            return adder
Jeremy Hylton's avatar
Jeremy Hylton committed
91

92 93
        inc = make_adder6(1)
        plus10 = make_adder6(10)
Jeremy Hylton's avatar
Jeremy Hylton committed
94

95 96
        self.assertEqual(inc(1), 11) # there's only one global
        self.assertEqual(plus10(-2), 8)
Jeremy Hylton's avatar
Jeremy Hylton committed
97

98
    def testNearestEnclosingScope(self):
Jeremy Hylton's avatar
Jeremy Hylton committed
99

100 101 102 103 104 105 106
        def f(x):
            def g(y):
                x = 42 # check that this masks binding in f()
                def h(z):
                    return x + z
                return h
            return g(2)
Jeremy Hylton's avatar
Jeremy Hylton committed
107

108 109
        test_func = f(10)
        self.assertEqual(test_func(5), 47)
Jeremy Hylton's avatar
Jeremy Hylton committed
110

111
    def testMixedFreevarsAndCellvars(self):
Jeremy Hylton's avatar
Jeremy Hylton committed
112

113 114
        def identity(x):
            return x
Jeremy Hylton's avatar
Jeremy Hylton committed
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
        def f(x, y, z):
            def g(a, b, c):
                a = a + x # 3
                def h():
                    # z * (4 + 9)
                    # 3 * 13
                    return identity(z * (b + y))
                y = c + z # 9
                return h
            return g

        g = f(1, 2, 3)
        h = g(2, 4, 6)
        self.assertEqual(h(), 39)

    def testFreeVarInMethod(self):

        def test():
            method_and_var = "var"
            class Test:
                def method_and_var(self):
                    return "method"
                def test(self):
                    return method_and_var
                def actual_global(self):
                    return str("global")
                def str(self):
                    return str(self)
            return Test()

        t = test()
        self.assertEqual(t.test(), "var")
        self.assertEqual(t.method_and_var(), "method")
        self.assertEqual(t.actual_global(), "global")

        method_and_var = "var"
        class Test:
            # this class is not nested, so the rules are different
            def method_and_var(self):
                return "method"
            def test(self):
                return method_and_var
            def actual_global(self):
                return str("global")
            def str(self):
                return str(self)

        t = Test()
        self.assertEqual(t.test(), "var")
        self.assertEqual(t.method_and_var(), "method")
        self.assertEqual(t.actual_global(), "global")

168 169 170 171 172 173 174 175 176 177 178
    def testCellIsKwonlyArg(self):
        # Issue 1409: Initialisation of a cell value,
        # when it comes from a keyword-only parameter
        def foo(*, a=17):
            def bar():
                return a + 5
            return bar() + 3

        self.assertEqual(foo(a=42), 50)
        self.assertEqual(foo(), 25)

179 180 181 182 183 184 185 186 187 188 189
    def testRecursion(self):

        def f(x):
            def fact(n):
                if n == 0:
                    return 1
                else:
                    return n * fact(n - 1)
            if x >= 0:
                return fact(x)
            else:
190
                raise ValueError("x must be >= 0")
191 192 193 194 195 196

        self.assertEqual(f(6), 720)


    def testUnoptimizedNamespaces(self):

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        check_syntax_error(self, """if 1:
            def unoptimized_clash1(strip):
                def f(s):
                    from sys import *
                    return getrefcount(s) # ambiguity: free or local
                return f
            """)

        check_syntax_error(self, """if 1:
            def unoptimized_clash2():
                from sys import *
                def f(s):
                    return getrefcount(s) # ambiguity: global or local
                return f
            """)

        check_syntax_error(self, """if 1:
            def unoptimized_clash2():
                from sys import *
                def g():
                    def f(s):
                        return getrefcount(s) # ambiguity: global or local
                    return f
            """)

        check_syntax_error(self, """if 1:
            def f():
                def g():
                    from sys import *
                    return getrefcount # global or local?
            """)
228

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    def testLambdas(self):

        f1 = lambda x: lambda y: x + y
        inc = f1(1)
        plus10 = f1(10)
        self.assertEqual(inc(1), 2)
        self.assertEqual(plus10(5), 15)

        f2 = lambda x: (lambda : lambda y: x + y)()
        inc = f2(1)
        plus10 = f2(10)
        self.assertEqual(inc(1), 2)
        self.assertEqual(plus10(5), 15)

        f3 = lambda x: lambda y: global_x + y
        global_x = 1
        inc = f3(None)
        self.assertEqual(inc(2), 3)

        f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y)
        g = f8(1, 2, 3)
        h = g(2, 4, 6)
        self.assertEqual(h(), 18)

    def testUnboundLocal(self):

        def errorInOuter():
256
            print(y)
257 258 259 260 261 262 263 264 265 266
            def inner():
                return y
            y = 1

        def errorInInner():
            def inner():
                return y
            inner()
            y = 1

267 268
        self.assertRaises(UnboundLocalError, errorInOuter)
        self.assertRaises(NameError, errorInInner)
269

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    def testUnboundLocal_AfterDel(self):
        # #4617: It is now legal to delete a cell variable.
        # The following functions must obviously compile,
        # and give the correct error when accessing the deleted name.
        def errorInOuter():
            y = 1
            del y
            print(y)
            def inner():
                return y

        def errorInInner():
            def inner():
                return y
            y = 1
            del y
            inner()

        self.assertRaises(UnboundLocalError, errorInOuter)
        self.assertRaises(NameError, errorInInner)

    def testUnboundLocal_AugAssign(self):
292
        # test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation
293 294 295 296 297 298 299 300 301 302 303
        exec("""if 1:
            global_x = 1
            def f():
                global_x += 1
            try:
                f()
            except UnboundLocalError:
                pass
            else:
                fail('scope of global_x not correctly determined')
            """, {'fail': self.fail})
304

305
    def testComplexDefinitions(self):
306

307 308 309 310
        def makeReturner(*lst):
            def returner():
                return lst
            return returner
Tim Peters's avatar
Tim Peters committed
311

312
        self.assertEqual(makeReturner(1,2,3)(), (1,2,3))
Tim Peters's avatar
Tim Peters committed
313

314 315 316 317
        def makeReturner2(**kwargs):
            def returner():
                return kwargs
            return returner
318

319
        self.assertEqual(makeReturner2(a=11)()['a'], 11)
320

321
    def testScopeOfGlobalStmt(self):
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        # Examples posted by Samuele Pedroni to python-dev on 3/1/2001

        exec("""if 1:
            # I
            x = 7
            def f():
                x = 1
                def g():
                    global x
                    def i():
                        def h():
                            return x
                        return h()
                    return i()
                return g()
            self.assertEqual(f(), 7)
            self.assertEqual(x, 7)

            # II
            x = 7
            def f():
                x = 1
                def g():
                    x = 2
                    def i():
                        def h():
                            return x
                        return h()
                    return i()
                return g()
            self.assertEqual(f(), 2)
            self.assertEqual(x, 7)

            # III
            x = 7
            def f():
                x = 1
                def g():
                    global x
                    x = 2
                    def i():
                        def h():
                            return x
                        return h()
                    return i()
                return g()
            self.assertEqual(f(), 2)
            self.assertEqual(x, 2)

            # IV
            x = 7
            def f():
                x = 3
                def g():
                    global x
                    x = 2
                    def i():
                        def h():
                            return x
                        return h()
                    return i()
                return g()
            self.assertEqual(f(), 2)
            self.assertEqual(x, 2)

            # XXX what about global statements in class blocks?
            # do they affect methods?

            x = 12
            class Global:
                global x
                x = 13
                def set(self, val):
                    x = val
                def get(self):
                    return x

            g = Global()
            self.assertEqual(g.get(), 13)
            g.set(15)
            self.assertEqual(g.get(), 13)
            """)
404

405
    def testLeaks(self):
406

407 408
        class Foo:
            count = 0
Tim Peters's avatar
Tim Peters committed
409

410 411
            def __init__(self):
                Foo.count += 1
412

413 414
            def __del__(self):
                Foo.count -= 1
415

416 417 418 419 420
        def f1():
            x = Foo()
            def f2():
                return x
            f2()
Tim Peters's avatar
Tim Peters committed
421

422 423
        for i in range(100):
            f1()
424

425
        self.assertEqual(Foo.count, 0)
426

427
    def testClassAndGlobal(self):
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
        exec("""if 1:
            def test(x):
                class Foo:
                    global x
                    def __call__(self, y):
                        return x + y
                return Foo()

            x = 0
            self.assertEqual(test(6)(2), 8)
            x = -1
            self.assertEqual(test(3)(2), 5)

            looked_up_by_load_name = False
            class X:
                # Implicit globals inside classes are be looked up by LOAD_NAME, not
                # LOAD_GLOBAL.
                locals()['looked_up_by_load_name'] = True
                passed = looked_up_by_load_name

            self.assertTrue(X.passed)
            """)
451

452
    def testLocalsFunction(self):
453

454 455 456 457 458 459 460 461
        def f(x):
            def g(y):
                def h(z):
                    return y + z
                w = x + y
                y += 3
                return locals()
            return g
462

463
        d = f(2)(4)
464
        self.assertIn('h', d)
465 466
        del d['h']
        self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6})
467

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    def testLocalsClass(self):
        # This test verifies that calling locals() does not pollute
        # the local namespace of the class with free variables.  Old
        # versions of Python had a bug, where a free variable being
        # passed through a class namespace would be inserted into
        # locals() by locals() or exec or a trace function.
        #
        # The real bug lies in frame code that copies variables
        # between fast locals and the locals dict, e.g. when executing
        # a trace function.

        def f(x):
            class C:
                x = 12
                def m(self):
                    return x
                locals()
            return C

        self.assertEqual(f(1).x, 12)

        def f(x):
            class C:
                y = x
                def m(self):
                    return x
                z = list(locals())
            return C

        varnames = f(1).z
498 499
        self.assertNotIn("x", varnames)
        self.assertIn("y", varnames)
500

501
    @cpython_only
Georg Brandl's avatar
Georg Brandl committed
502 503 504 505 506 507
    def testLocalsClass_WithTrace(self):
        # Issue23728: after the trace function returns, the locals()
        # dictionary is used to update all variables, this used to
        # include free variables. But in class statements, free
        # variables are not inserted...
        import sys
508
        self.addCleanup(sys.settrace, sys.gettrace())
Georg Brandl's avatar
Georg Brandl committed
509
        sys.settrace(lambda a,b,c:None)
510
        x = 12
Georg Brandl's avatar
Georg Brandl committed
511

512 513 514
        class C:
            def f(self):
                return x
Georg Brandl's avatar
Georg Brandl committed
515

516
        self.assertEqual(x, 12) # Used to raise UnboundLocalError
Georg Brandl's avatar
Georg Brandl committed
517

518 519
    def testBoundAndFree(self):
        # var is bound and free in class
520

521 522 523 524 525 526
        def f(x):
            class C:
                def m(self):
                    return x
                a = x
            return C
527

528 529
        inst = f(3)()
        self.assertEqual(inst.a, inst.m())
530

531
    @cpython_only
532
    def testInteractionWithTraceFunc(self):
533

534 535 536
        import sys
        def tracer(a,b,c):
            return tracer
537

538 539 540 541 542 543
        def adaptgetter(name, klass, getter):
            kind, des = getter
            if kind == 1:       # AV happens when stepping from this line to next
                if des == "":
                    des = "_%s__%s" % (klass.__name__, name)
                return lambda obj: getattr(obj, des)
544

545 546
        class TestClass:
            pass
547

548
        self.addCleanup(sys.settrace, sys.gettrace())
549 550 551
        sys.settrace(tracer)
        adaptgetter("foo", TestClass, (1, ""))
        sys.settrace(None)
552

553
        self.assertRaises(TypeError, sys.settrace)
554

555
    def testEvalExecFreeVars(self):
556

557 558
        def f(x):
            return lambda: x + 1
559

560
        g = f(3)
561
        self.assertRaises(TypeError, eval, g.__code__)
562

563
        try:
564
            exec(g.__code__, {})
565 566 567 568
        except TypeError:
            pass
        else:
            self.fail("exec should have failed, because code contained free vars")
569

570
    def testListCompLocalVars(self):
571

572
        try:
573
            print(bad)
574 575 576
        except NameError:
            pass
        else:
577
            print("bad should not be defined")
578

579 580
        def x():
            [bad for s in 'a b' for bad in s.split()]
581

582 583
        x()
        try:
584
            print(bad)
585 586
        except NameError:
            pass
587

588
    def testEvalFreeVars(self):
589

590 591 592 593 594 595 596 597
        def f(x):
            def g():
                x
                eval("x + 1")
            return g

        f(4)()

Christian Heimes's avatar
Christian Heimes committed
598 599 600 601 602 603 604
    def testFreeingCell(self):
        # Test what happens when a finalizer accesses
        # the cell where the object was stored.
        class Special:
            def __del__(self):
                nestedcell_get()

605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    def testNonLocalFunction(self):

        def f(x):
            def inc():
                nonlocal x
                x += 1
                return x
            def dec():
                nonlocal x
                x -= 1
                return x
            return inc, dec

        inc, dec = f(0)
        self.assertEqual(inc(), 1)
        self.assertEqual(inc(), 2)
        self.assertEqual(dec(), 1)
        self.assertEqual(dec(), 0)

    def testNonLocalMethod(self):
        def f(x):
            class c:
                def inc(self):
                    nonlocal x
                    x += 1
                    return x
                def dec(self):
                    nonlocal x
                    x -= 1
                    return x
            return c()
        c = f(0)
        self.assertEqual(c.inc(), 1)
        self.assertEqual(c.inc(), 2)
        self.assertEqual(c.dec(), 1)
        self.assertEqual(c.dec(), 0)

642 643 644 645 646 647 648
    def testGlobalInParallelNestedFunctions(self):
        # A symbol table bug leaked the global statement from one
        # function to other nested functions in the same block.
        # This test verifies that a global statement in the first
        # function does not affect the second function.
        local_ns = {}
        global_ns = {}
649 650 651 652 653 654 655 656 657 658 659 660 661 662
        exec("""if 1:
            def f():
                y = 1
                def g():
                    global y
                    return y
                def h():
                    return y + 1
                return g, h
            y = 9
            g, h = f()
            result9 = g()
            result2 = h()
            """, local_ns, global_ns)
663 664 665
        self.assertEqual(2, global_ns["result2"])
        self.assertEqual(9, global_ns["result9"])

666 667 668 669 670 671 672 673 674 675 676 677
    def testNonLocalClass(self):

        def f(x):
            class c:
                nonlocal x
                x += 1
                def get(self):
                    return x
            return c()

        c = f(0)
        self.assertEqual(c.get(), 1)
678
        self.assertNotIn("x", c.__class__.__dict__)
679

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

    def testNonLocalGenerator(self):

        def f(x):
            def g(y):
                nonlocal x
                for i in range(y):
                    x += 1
                    yield x
            return g

        g = f(0)
        self.assertEqual(list(g(5)), [1, 2, 3, 4, 5])

    def testNestedNonLocal(self):

        def f(x):
            def g():
                nonlocal x
                x -= 2
                def h():
                    nonlocal x
                    x += 4
                    return x
                return h
            return g

        g = f(1)
        h = g()
        self.assertEqual(h(), 3)

711 712 713 714 715 716 717
    def testTopIsNotSignificant(self):
        # See #9997.
        def top(a):
            pass
        def b():
            global a

718 719 720 721 722 723 724 725 726 727 728 729 730
    def testClassNamespaceOverridesClosure(self):
        # See #17853.
        x = 42
        class X:
            locals()["x"] = 43
            y = x
        self.assertEqual(X.y, 43)
        class X:
            locals()["x"] = 43
            del x
        self.assertFalse(hasattr(X, "x"))
        self.assertEqual(x, 42)

731 732 733 734 735 736 737 738 739 740 741 742 743
    @cpython_only
    def testCellLeak(self):
        # Issue 17927.
        #
        # The issue was that if self was part of a cycle involving the
        # frame of a method call, *and* the method contained a nested
        # function referencing self, thereby forcing 'self' into a
        # cell, setting self to None would not be enough to break the
        # frame -- the frame had another reference to the instance,
        # which could not be cleared by the code running in the frame
        # (though it will be cleared when the frame is collected).
        # Without the lambda, setting self to None is enough to break
        # the cycle.
744
        class Tester:
745 746 747 748 749 750 751 752 753 754
            def dig(self):
                if 0:
                    lambda: self
                try:
                    1/0
                except Exception as exc:
                    self.exc = exc
                self = None  # Break the cycle
        tester = Tester()
        tester.dig()
755
        ref = weakref.ref(tester)
756
        del tester
757
        self.assertIsNone(ref())
758

759 760

if __name__ == '__main__':
761
    unittest.main()