Back to index

python3.2  3.2.2
Public Member Functions
test.test_scope.ScopeTests Class Reference

List of all members.

Public Member Functions

def testSimpleNesting
def testExtraNesting
def testSimpleAndRebinding
def testNestingGlobalNoFree
def testNestingThroughClass
def testNestingPlusFreeRefToGlobal
def testNearestEnclosingScope
def testMixedFreevarsAndCellvars
def testFreeVarInMethod
def testCellIsKwonlyArg
def testRecursion
def testUnoptimizedNamespaces
def testLambdas
def testUnboundLocal
def testUnboundLocal_AfterDel
def testUnboundLocal_AugAssign
def testComplexDefinitions
def testScopeOfGlobalStmt
def testLeaks
def testClassAndGlobal
def testLocalsFunction
def testLocalsClass
def testLocalsClass_WithTrace
def testBoundAndFree
def testInteractionWithTraceFunc
def testEvalExecFreeVars
def testListCompLocalVars
def testEvalFreeVars
def testFreeingCell
def testNonLocalFunction
def testNonLocalMethod
def testGlobalInParallelNestedFunctions
def testNonLocalClass
def testNonLocalGenerator
def testNestedNonLocal
def testTopIsNotSignificant

Detailed Description

Definition at line 5 of file test_scope.py.


Member Function Documentation

Definition at line 517 of file test_scope.py.

00517 
00518     def testBoundAndFree(self):
00519         # var is bound and free in class
00520 
00521         def f(x):
00522             class C:
00523                 def m(self):
00524                     return x
00525                 a = x
00526             return C
00527 
00528         inst = f(3)()
00529         self.assertEqual(inst.a, inst.m())

Here is the call graph for this function:

Definition at line 166 of file test_scope.py.

00166 
00167     def testCellIsKwonlyArg(self):
00168         # Issue 1409: Initialisation of a cell value,
00169         # when it comes from a keyword-only parameter
00170         def foo(*, a=17):
00171             def bar():
00172                 return a + 5
00173             return bar() + 3
00174 
00175         self.assertEqual(foo(a=42), 50)
00176         self.assertEqual(foo(), 25)

Here is the call graph for this function:

Definition at line 425 of file test_scope.py.

00425 
00426     def testClassAndGlobal(self):
00427 
00428         exec("""if 1:
00429             def test(x):
00430                 class Foo:
00431                     global x
00432                     def __call__(self, y):
00433                         return x + y
00434                 return Foo()
00435 
00436             x = 0
00437             self.assertEqual(test(6)(2), 8)
00438             x = -1
00439             self.assertEqual(test(3)(2), 5)
00440 
00441             looked_up_by_load_name = False
00442             class X:
00443                 # Implicit globals inside classes are be looked up by LOAD_NAME, not
00444                 # LOAD_GLOBAL.
00445                 locals()['looked_up_by_load_name'] = True
00446                 passed = looked_up_by_load_name
00447 
00448             self.assertTrue(X.passed)
00449             """)

Definition at line 303 of file test_scope.py.

00303 
00304     def testComplexDefinitions(self):
00305 
00306         def makeReturner(*lst):
00307             def returner():
00308                 return lst
00309             return returner
00310 
00311         self.assertEqual(makeReturner(1,2,3)(), (1,2,3))
00312 
00313         def makeReturner2(**kwargs):
00314             def returner():
00315                 return kwargs
00316             return returner
00317 
00318         self.assertEqual(makeReturner2(a=11)()['a'], 11)

Here is the call graph for this function:

Definition at line 552 of file test_scope.py.

00552 
00553     def testEvalExecFreeVars(self):
00554 
00555         def f(x):
00556             return lambda: x + 1
00557 
00558         g = f(3)
00559         self.assertRaises(TypeError, eval, g.__code__)
00560 
00561         try:
00562             exec(g.__code__, {})
00563         except TypeError:
00564             pass
00565         else:
00566             self.fail("exec should have failed, because code contained free vars")

Here is the call graph for this function:

Definition at line 585 of file test_scope.py.

00585 
00586     def testEvalFreeVars(self):
00587 
00588         def f(x):
00589             def g():
00590                 x
00591                 eval("x + 1")
00592             return g
00593 
00594         f(4)()

Definition at line 20 of file test_scope.py.

00020 
00021     def testExtraNesting(self):
00022 
00023         def make_adder2(x):
00024             def extra(): # check freevars passing through non-use scopes
00025                 def adder(y):
00026                     return x + y
00027                 return adder
00028             return extra()
00029 
00030         inc = make_adder2(1)
00031         plus10 = make_adder2(10)
00032 
00033         self.assertEqual(inc(1), 2)
00034         self.assertEqual(plus10(-2), 8)

Here is the call graph for this function:

Definition at line 595 of file test_scope.py.

00595 
00596     def testFreeingCell(self):
00597         # Test what happens when a finalizer accesses
00598         # the cell where the object was stored.
00599         class Special:
00600             def __del__(self):
00601                 nestedcell_get()

Definition at line 129 of file test_scope.py.

00129 
00130     def testFreeVarInMethod(self):
00131 
00132         def test():
00133             method_and_var = "var"
00134             class Test:
00135                 def method_and_var(self):
00136                     return "method"
00137                 def test(self):
00138                     return method_and_var
00139                 def actual_global(self):
00140                     return str("global")
00141                 def str(self):
00142                     return str(self)
00143             return Test()
00144 
00145         t = test()
00146         self.assertEqual(t.test(), "var")
00147         self.assertEqual(t.method_and_var(), "method")
00148         self.assertEqual(t.actual_global(), "global")
00149 
00150         method_and_var = "var"
00151         class Test:
00152             # this class is not nested, so the rules are different
00153             def method_and_var(self):
00154                 return "method"
00155             def test(self):
00156                 return method_and_var
00157             def actual_global(self):
00158                 return str("global")
00159             def str(self):
00160                 return str(self)
00161 
00162         t = Test()
00163         self.assertEqual(t.test(), "var")
00164         self.assertEqual(t.method_and_var(), "method")
00165         self.assertEqual(t.actual_global(), "global")

Here is the call graph for this function:

Definition at line 639 of file test_scope.py.

00639 
00640     def testGlobalInParallelNestedFunctions(self):
00641         # A symbol table bug leaked the global statement from one
00642         # function to other nested functions in the same block.
00643         # This test verifies that a global statement in the first
00644         # function does not affect the second function.
00645         local_ns = {}
00646         global_ns = {}
00647         exec("""if 1:
00648             def f():
00649                 y = 1
00650                 def g():
00651                     global y
00652                     return y
00653                 def h():
00654                     return y + 1
00655                 return g, h
00656             y = 9
00657             g, h = f()
00658             result9 = g()
00659             result2 = h()
00660             """, local_ns, global_ns)
00661         self.assertEqual(2, global_ns["result2"])
00662         self.assertEqual(9, global_ns["result9"])

Here is the call graph for this function:

Definition at line 530 of file test_scope.py.

00530 
00531     def testInteractionWithTraceFunc(self):
00532 
00533         import sys
00534         def tracer(a,b,c):
00535             return tracer
00536 
00537         def adaptgetter(name, klass, getter):
00538             kind, des = getter
00539             if kind == 1:       # AV happens when stepping from this line to next
00540                 if des == "":
00541                     des = "_%s__%s" % (klass.__name__, name)
00542                 return lambda obj: getattr(obj, des)
00543 
00544         class TestClass:
00545             pass
00546 
00547         sys.settrace(tracer)
00548         adaptgetter("foo", TestClass, (1, ""))
00549         sys.settrace(None)
00550 
00551         self.assertRaises(TypeError, sys.settrace)

Here is the call graph for this function:

Definition at line 227 of file test_scope.py.

00227 
00228     def testLambdas(self):
00229 
00230         f1 = lambda x: lambda y: x + y
00231         inc = f1(1)
00232         plus10 = f1(10)
00233         self.assertEqual(inc(1), 2)
00234         self.assertEqual(plus10(5), 15)
00235 
00236         f2 = lambda x: (lambda : lambda y: x + y)()
00237         inc = f2(1)
00238         plus10 = f2(10)
00239         self.assertEqual(inc(1), 2)
00240         self.assertEqual(plus10(5), 15)
00241 
00242         f3 = lambda x: lambda y: global_x + y
00243         global_x = 1
00244         inc = f3(None)
00245         self.assertEqual(inc(2), 3)
00246 
00247         f8 = lambda x, y, z: lambda a, b, c: lambda : z * (b + y)
00248         g = f8(1, 2, 3)
00249         h = g(2, 4, 6)
00250         self.assertEqual(h(), 18)

Here is the call graph for this function:

Definition at line 403 of file test_scope.py.

00403 
00404     def testLeaks(self):
00405 
00406         class Foo:
00407             count = 0
00408 
00409             def __init__(self):
00410                 Foo.count += 1
00411 
00412             def __del__(self):
00413                 Foo.count -= 1
00414 
00415         def f1():
00416             x = Foo()
00417             def f2():
00418                 return x
00419             f2()
00420 
00421         for i in range(100):
00422             f1()
00423 
00424         self.assertEqual(Foo.count, 0)

Here is the call graph for this function:

Definition at line 567 of file test_scope.py.

00567 
00568     def testListCompLocalVars(self):
00569 
00570         try:
00571             print(bad)
00572         except NameError:
00573             pass
00574         else:
00575             print("bad should not be defined")
00576 
00577         def x():
00578             [bad for s in 'a b' for bad in s.split()]
00579 
00580         x()
00581         try:
00582             print(bad)
00583         except NameError:
00584             pass

Definition at line 466 of file test_scope.py.

00466 
00467     def testLocalsClass(self):
00468         # This test verifies that calling locals() does not pollute
00469         # the local namespace of the class with free variables.  Old
00470         # versions of Python had a bug, where a free variable being
00471         # passed through a class namespace would be inserted into
00472         # locals() by locals() or exec or a trace function.
00473         #
00474         # The real bug lies in frame code that copies variables
00475         # between fast locals and the locals dict, e.g. when executing
00476         # a trace function.
00477 
00478         def f(x):
00479             class C:
00480                 x = 12
00481                 def m(self):
00482                     return x
00483                 locals()
00484             return C
00485 
00486         self.assertEqual(f(1).x, 12)
00487 
00488         def f(x):
00489             class C:
00490                 y = x
00491                 def m(self):
00492                     return x
00493                 z = list(locals())
00494             return C
00495 
00496         varnames = f(1).z
00497         self.assertNotIn("x", varnames)
00498         self.assertIn("y", varnames)

Here is the call graph for this function:

Definition at line 499 of file test_scope.py.

00499 
00500     def testLocalsClass_WithTrace(self):
00501         # Issue23728: after the trace function returns, the locals()
00502         # dictionary is used to update all variables, this used to
00503         # include free variables. But in class statements, free
00504         # variables are not inserted...
00505         import sys
00506         sys.settrace(lambda a,b,c:None)
00507         try:
00508             x = 12
00509 
00510             class C:
00511                 def f(self):
00512                     return x
00513 
00514             self.assertEqual(x, 12) # Used to raise UnboundLocalError
00515         finally:
00516             sys.settrace(None)

Here is the call graph for this function:

Definition at line 450 of file test_scope.py.

00450 
00451     def testLocalsFunction(self):
00452 
00453         def f(x):
00454             def g(y):
00455                 def h(z):
00456                     return y + z
00457                 w = x + y
00458                 y += 3
00459                 return locals()
00460             return g
00461 
00462         d = f(2)(4)
00463         self.assertIn('h', d)
00464         del d['h']
00465         self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6})

Here is the call graph for this function:

Definition at line 109 of file test_scope.py.

00109 
00110     def testMixedFreevarsAndCellvars(self):
00111 
00112         def identity(x):
00113             return x
00114 
00115         def f(x, y, z):
00116             def g(a, b, c):
00117                 a = a + x # 3
00118                 def h():
00119                     # z * (4 + 9)
00120                     # 3 * 13
00121                     return identity(z * (b + y))
00122                 y = c + z # 9
00123                 return h
00124             return g
00125 
00126         g = f(1, 2, 3)
00127         h = g(2, 4, 6)
00128         self.assertEqual(h(), 39)

Here is the call graph for this function:

Definition at line 96 of file test_scope.py.

00096 
00097     def testNearestEnclosingScope(self):
00098 
00099         def f(x):
00100             def g(y):
00101                 x = 42 # check that this masks binding in f()
00102                 def h(z):
00103                     return x + z
00104                 return h
00105             return g(2)
00106 
00107         test_func = f(10)
00108         self.assertEqual(test_func(5), 47)

Here is the call graph for this function:

Definition at line 691 of file test_scope.py.

00691 
00692     def testNestedNonLocal(self):
00693 
00694         def f(x):
00695             def g():
00696                 nonlocal x
00697                 x -= 2
00698                 def h():
00699                     nonlocal x
00700                     x += 4
00701                     return x
00702                 return h
00703             return g
00704 
00705         g = f(1)
00706         h = g()
00707         self.assertEqual(h(), 3)

Here is the call graph for this function:

Definition at line 49 of file test_scope.py.

00049 
00050     def testNestingGlobalNoFree(self):
00051 
00052         def make_adder4(): # XXX add exta level of indirection
00053             def nest():
00054                 def nest():
00055                     def adder(y):
00056                         return global_x + y # check that plain old globals work
00057                     return adder
00058                 return nest()
00059             return nest()
00060 
00061         global_x = 1
00062         adder = make_adder4()
00063         self.assertEqual(adder(1), 2)
00064 
00065         global_x = 10
00066         self.assertEqual(adder(-2), 8)

Here is the call graph for this function:

Definition at line 81 of file test_scope.py.

00081 
00082     def testNestingPlusFreeRefToGlobal(self):
00083 
00084         def make_adder6(x):
00085             global global_nest_x
00086             def adder(y):
00087                 return global_nest_x + y
00088             global_nest_x = x
00089             return adder
00090 
00091         inc = make_adder6(1)
00092         plus10 = make_adder6(10)
00093 
00094         self.assertEqual(inc(1), 11) # there's only one global
00095         self.assertEqual(plus10(-2), 8)

Here is the call graph for this function:

Definition at line 67 of file test_scope.py.

00067 
00068     def testNestingThroughClass(self):
00069 
00070         def make_adder5(x):
00071             class Adder:
00072                 def __call__(self, y):
00073                     return x + y
00074             return Adder()
00075 
00076         inc = make_adder5(1)
00077         plus10 = make_adder5(10)
00078 
00079         self.assertEqual(inc(1), 2)
00080         self.assertEqual(plus10(-2), 8)

Here is the call graph for this function:

Definition at line 663 of file test_scope.py.

00663 
00664     def testNonLocalClass(self):
00665 
00666         def f(x):
00667             class c:
00668                 nonlocal x
00669                 x += 1
00670                 def get(self):
00671                     return x
00672             return c()
00673 
00674         c = f(0)
00675         self.assertEqual(c.get(), 1)
00676         self.assertNotIn("x", c.__class__.__dict__)
00677 

Here is the call graph for this function:

Definition at line 602 of file test_scope.py.

00602 
00603     def testNonLocalFunction(self):
00604 
00605         def f(x):
00606             def inc():
00607                 nonlocal x
00608                 x += 1
00609                 return x
00610             def dec():
00611                 nonlocal x
00612                 x -= 1
00613                 return x
00614             return inc, dec
00615 
00616         inc, dec = f(0)
00617         self.assertEqual(inc(), 1)
00618         self.assertEqual(inc(), 2)
00619         self.assertEqual(dec(), 1)
00620         self.assertEqual(dec(), 0)

Here is the call graph for this function:

Definition at line 678 of file test_scope.py.

00678 
00679     def testNonLocalGenerator(self):
00680 
00681         def f(x):
00682             def g(y):
00683                 nonlocal x
00684                 for i in range(y):
00685                     x += 1
00686                     yield x
00687             return g
00688 
00689         g = f(0)
00690         self.assertEqual(list(g(5)), [1, 2, 3, 4, 5])

Here is the call graph for this function:

Definition at line 621 of file test_scope.py.

00621 
00622     def testNonLocalMethod(self):
00623         def f(x):
00624             class c:
00625                 def inc(self):
00626                     nonlocal x
00627                     x += 1
00628                     return x
00629                 def dec(self):
00630                     nonlocal x
00631                     x -= 1
00632                     return x
00633             return c()
00634         c = f(0)
00635         self.assertEqual(c.inc(), 1)
00636         self.assertEqual(c.inc(), 2)
00637         self.assertEqual(c.dec(), 1)
00638         self.assertEqual(c.dec(), 0)

Here is the call graph for this function:

Definition at line 177 of file test_scope.py.

00177 
00178     def testRecursion(self):
00179 
00180         def f(x):
00181             def fact(n):
00182                 if n == 0:
00183                     return 1
00184                 else:
00185                     return n * fact(n - 1)
00186             if x >= 0:
00187                 return fact(x)
00188             else:
00189                 raise ValueError("x must be >= 0")
00190 
00191         self.assertEqual(f(6), 720)
00192 

Here is the call graph for this function:

Definition at line 319 of file test_scope.py.

00319 
00320     def testScopeOfGlobalStmt(self):
00321         # Examples posted by Samuele Pedroni to python-dev on 3/1/2001
00322 
00323         exec("""if 1:
00324             # I
00325             x = 7
00326             def f():
00327                 x = 1
00328                 def g():
00329                     global x
00330                     def i():
00331                         def h():
00332                             return x
00333                         return h()
00334                     return i()
00335                 return g()
00336             self.assertEqual(f(), 7)
00337             self.assertEqual(x, 7)
00338 
00339             # II
00340             x = 7
00341             def f():
00342                 x = 1
00343                 def g():
00344                     x = 2
00345                     def i():
00346                         def h():
00347                             return x
00348                         return h()
00349                     return i()
00350                 return g()
00351             self.assertEqual(f(), 2)
00352             self.assertEqual(x, 7)
00353 
00354             # III
00355             x = 7
00356             def f():
00357                 x = 1
00358                 def g():
00359                     global x
00360                     x = 2
00361                     def i():
00362                         def h():
00363                             return x
00364                         return h()
00365                     return i()
00366                 return g()
00367             self.assertEqual(f(), 2)
00368             self.assertEqual(x, 2)
00369 
00370             # IV
00371             x = 7
00372             def f():
00373                 x = 3
00374                 def g():
00375                     global x
00376                     x = 2
00377                     def i():
00378                         def h():
00379                             return x
00380                         return h()
00381                     return i()
00382                 return g()
00383             self.assertEqual(f(), 2)
00384             self.assertEqual(x, 2)
00385 
00386             # XXX what about global statements in class blocks?
00387             # do they affect methods?
00388 
00389             x = 12
00390             class Global:
00391                 global x
00392                 x = 13
00393                 def set(self, val):
00394                     x = val
00395                 def get(self):
00396                     return x
00397 
00398             g = Global()
00399             self.assertEqual(g.get(), 13)
00400             g.set(15)
00401             self.assertEqual(g.get(), 13)
00402             """)

Definition at line 35 of file test_scope.py.

00035 
00036     def testSimpleAndRebinding(self):
00037 
00038         def make_adder3(x):
00039             def adder(y):
00040                 return x + y
00041             x = x + 1 # check tracking of assignment to x in defining scope
00042             return adder
00043 
00044         inc = make_adder3(0)
00045         plus10 = make_adder3(9)
00046 
00047         self.assertEqual(inc(1), 2)
00048         self.assertEqual(plus10(-2), 8)

Here is the call graph for this function:

Definition at line 7 of file test_scope.py.

00007 
00008     def testSimpleNesting(self):
00009 
00010         def make_adder(x):
00011             def adder(y):
00012                 return x + y
00013             return adder
00014 
00015         inc = make_adder(1)
00016         plus10 = make_adder(10)
00017 
00018         self.assertEqual(inc(1), 2)
00019         self.assertEqual(plus10(-2), 8)

Here is the call graph for this function:

Definition at line 708 of file test_scope.py.

00708 
00709     def testTopIsNotSignificant(self):
00710         # See #9997.
00711         def top(a):
00712             pass
00713         def b():
00714             global a
00715 
00716 

Definition at line 251 of file test_scope.py.

00251 
00252     def testUnboundLocal(self):
00253 
00254         def errorInOuter():
00255             print(y)
00256             def inner():
00257                 return y
00258             y = 1
00259 
00260         def errorInInner():
00261             def inner():
00262                 return y
00263             inner()
00264             y = 1
00265 
00266         self.assertRaises(UnboundLocalError, errorInOuter)
00267         self.assertRaises(NameError, errorInInner)

Here is the call graph for this function:

Definition at line 268 of file test_scope.py.

00268 
00269     def testUnboundLocal_AfterDel(self):
00270         # #4617: It is now legal to delete a cell variable.
00271         # The following functions must obviously compile,
00272         # and give the correct error when accessing the deleted name.
00273         def errorInOuter():
00274             y = 1
00275             del y
00276             print(y)
00277             def inner():
00278                 return y
00279 
00280         def errorInInner():
00281             def inner():
00282                 return y
00283             y = 1
00284             del y
00285             inner()
00286 
00287         self.assertRaises(UnboundLocalError, errorInOuter)
00288         self.assertRaises(NameError, errorInInner)

Here is the call graph for this function:

Definition at line 289 of file test_scope.py.

00289 
00290     def testUnboundLocal_AugAssign(self):
00291         # test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation
00292         exec("""if 1:
00293             global_x = 1
00294             def f():
00295                 global_x += 1
00296             try:
00297                 f()
00298             except UnboundLocalError:
00299                 pass
00300             else:
00301                 fail('scope of global_x not correctly determined')
00302             """, {'fail': self.fail})

Here is the call graph for this function:

Definition at line 193 of file test_scope.py.

00193 
00194     def testUnoptimizedNamespaces(self):
00195 
00196         check_syntax_error(self, """if 1:
00197             def unoptimized_clash1(strip):
00198                 def f(s):
00199                     from sys import *
00200                     return getrefcount(s) # ambiguity: free or local
00201                 return f
00202             """)
00203 
00204         check_syntax_error(self, """if 1:
00205             def unoptimized_clash2():
00206                 from sys import *
00207                 def f(s):
00208                     return getrefcount(s) # ambiguity: global or local
00209                 return f
00210             """)
00211 
00212         check_syntax_error(self, """if 1:
00213             def unoptimized_clash2():
00214                 from sys import *
00215                 def g():
00216                     def f(s):
00217                         return getrefcount(s) # ambiguity: global or local
00218                     return f
00219             """)
00220 
00221         check_syntax_error(self, """if 1:
00222             def f():
00223                 def g():
00224                     from sys import *
00225                     return getrefcount # global or local?
00226             """)

Here is the call graph for this function:


The documentation for this class was generated from the following file: