2 from test
.test_support
import check_syntax_error
, run_unittest
5 warnings
.filterwarnings("ignore", r
"import \*", SyntaxWarning, "<test string>")
6 warnings
.filterwarnings("ignore", r
"import \*", SyntaxWarning, "<string>")
8 class ScopeTests(unittest
.TestCase
):
10 def testSimpleNesting(self
):
18 plus10
= make_adder(10)
20 self
.assertEqual(inc(1), 2)
21 self
.assertEqual(plus10(-2), 8)
23 def testExtraNesting(self
):
26 def extra(): # check freevars passing through non-use scopes
33 plus10
= make_adder2(10)
35 self
.assertEqual(inc(1), 2)
36 self
.assertEqual(plus10(-2), 8)
38 def testSimpleAndRebinding(self
):
43 x
= x
+ 1 # check tracking of assignment to x in defining scope
47 plus10
= make_adder3(9)
49 self
.assertEqual(inc(1), 2)
50 self
.assertEqual(plus10(-2), 8)
52 def testNestingGlobalNoFree(self
):
54 def make_adder4(): # XXX add exta level of indirection
58 return global_x
+ y
# check that plain old globals work
65 self
.assertEqual(adder(1), 2)
68 self
.assertEqual(adder(-2), 8)
70 def testNestingThroughClass(self
):
74 def __call__(self
, y
):
79 plus10
= make_adder5(10)
81 self
.assertEqual(inc(1), 2)
82 self
.assertEqual(plus10(-2), 8)
84 def testNestingPlusFreeRefToGlobal(self
):
89 return global_nest_x
+ y
94 plus10
= make_adder6(10)
96 self
.assertEqual(inc(1), 11) # there's only one global
97 self
.assertEqual(plus10(-2), 8)
99 def testNearestEnclosingScope(self
):
103 x
= 42 # check that this masks binding in f()
110 self
.assertEqual(test_func(5), 47)
112 def testMixedFreevarsAndCellvars(self
):
123 return identity(z
* (b
+ y
))
130 self
.assertEqual(h(), 39)
132 def testFreeVarInMethod(self
):
135 method_and_var
= "var"
137 def method_and_var(self
):
140 return method_and_var
141 def actual_global(self
):
148 self
.assertEqual(t
.test(), "var")
149 self
.assertEqual(t
.method_and_var(), "method")
150 self
.assertEqual(t
.actual_global(), "global")
152 method_and_var
= "var"
154 # this class is not nested, so the rules are different
155 def method_and_var(self
):
158 return method_and_var
159 def actual_global(self
):
165 self
.assertEqual(t
.test(), "var")
166 self
.assertEqual(t
.method_and_var(), "method")
167 self
.assertEqual(t
.actual_global(), "global")
169 def testRecursion(self
):
176 return n
* fact(n
- 1)
180 raise ValueError, "x must be >= 0"
182 self
.assertEqual(f(6), 720)
185 def testUnoptimizedNamespaces(self
):
187 check_syntax_error(self
, """\
188 def unoptimized_clash1(strip):
191 return strip(s) # ambiguity: free or local
195 check_syntax_error(self
, """\
196 def unoptimized_clash2():
199 return strip(s) # ambiguity: global or local
203 check_syntax_error(self
, """\
204 def unoptimized_clash2():
208 return strip(s) # ambiguity: global or local
212 # XXX could allow this for exec with const argument, but what's the point
213 check_syntax_error(self
, """\
221 check_syntax_error(self
, """\
225 del x # can't del name
228 check_syntax_error(self
, """\
232 return strip # global or local?
235 # and verify a few cases that should work
254 def testLambdas(self
):
256 f1
= lambda x
: lambda y
: x
+ y
259 self
.assertEqual(inc(1), 2)
260 self
.assertEqual(plus10(5), 15)
262 f2
= lambda x
: (lambda : lambda y
: x
+ y
)()
265 self
.assertEqual(inc(1), 2)
266 self
.assertEqual(plus10(5), 15)
268 f3
= lambda x
: lambda y
: global_x
+ y
271 self
.assertEqual(inc(2), 3)
273 f8
= lambda x
, y
, z
: lambda a
, b
, c
: lambda : z
* (b
+ y
)
276 self
.assertEqual(h(), 18)
278 def testUnboundLocal(self
):
292 self
.assertRaises(UnboundLocalError, errorInOuter
)
293 self
.assertRaises(NameError, errorInInner
)
295 # test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation
302 except UnboundLocalError:
305 fail('scope of global_x not correctly determined')
306 """ in {'fail': self
.fail
}
308 def testComplexDefinitions(self
):
310 def makeReturner(*lst
):
315 self
.assertEqual(makeReturner(1,2,3)(), (1,2,3))
317 def makeReturner2(**kwargs
):
322 self
.assertEqual(makeReturner2(a
=11)()['a'], 11)
324 def makeAddPair((a
, b
)):
326 return (a
+ c
, b
+ d
)
329 self
.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202))
331 def testScopeOfGlobalStmt(self
):
332 # Examples posted by Samuele Pedroni to python-dev on 3/1/2001
347 self.assertEqual(f(), 7)
348 self.assertEqual(x, 7)
362 self.assertEqual(f(), 2)
363 self.assertEqual(x, 7)
378 self.assertEqual(f(), 2)
379 self.assertEqual(x, 2)
394 self.assertEqual(f(), 2)
395 self.assertEqual(x, 2)
397 # XXX what about global statements in class blocks?
398 # do they affect methods?
410 self.assertEqual(g.get(), 13)
412 self.assertEqual(g.get(), 13)
435 self
.assertEqual(Foo
.count
, 0)
437 def testClassAndGlobal(self
):
443 def __call__(self, y):
448 self.assertEqual(test(6)(2), 8)
450 self.assertEqual(test(3)(2), 5)
452 looked_up_by_load_name = False
454 # Implicit globals inside classes are be looked up by LOAD_NAME, not
456 locals()['looked_up_by_load_name'] = True
457 passed = looked_up_by_load_name
459 self.assertTrue(X.passed)
462 def testLocalsFunction(self
):
474 self
.assertTrue(d
.has_key('h'))
476 self
.assertEqual(d
, {'x': 2, 'y': 7, 'w': 6})
478 def testLocalsClass(self
):
479 # This test verifies that calling locals() does not pollute
480 # the local namespace of the class with free variables. Old
481 # versions of Python had a bug, where a free variable being
482 # passed through a class namespace would be inserted into
483 # locals() by locals() or exec or a trace function.
485 # The real bug lies in frame code that copies variables
486 # between fast locals and the locals dict, e.g. when executing
497 self
.assertEqual(f(1).x
, 12)
508 self
.assertTrue("x" not in varnames
)
509 self
.assertTrue("y" in varnames
)
511 def testLocalsClass_WithTrace(self
):
512 # Issue23728: after the trace function returns, the locals()
513 # dictionary is used to update all variables, this used to
514 # include free variables. But in class statements, free
515 # variables are not inserted...
517 sys
.settrace(lambda a
,b
,c
:None)
525 self
.assertEquals(x
, 12) # Used to raise UnboundLocalError
529 def testBoundAndFree(self
):
530 # var is bound and free in class
540 self
.assertEqual(inst
.a
, inst
.m())
542 def testInteractionWithTraceFunc(self
):
548 def adaptgetter(name
, klass
, getter
):
550 if kind
== 1: # AV happens when stepping from this line to next
552 des
= "_%s__%s" % (klass
.__name
__, name
)
553 return lambda obj
: getattr(obj
, des
)
559 adaptgetter("foo", TestClass
, (1, ""))
562 self
.assertRaises(TypeError, sys
.settrace
)
564 def testEvalExecFreeVars(self
):
570 self
.assertRaises(TypeError, eval, g
.func_code
)
573 exec g
.func_code
in {}
577 self
.fail("exec should have failed, because code contained free vars")
579 def testListCompLocalVars(self
):
586 print "bad should not be defined"
589 [bad
for s
in 'a b' for bad
in s
.split()]
597 def testEvalFreeVars(self
):
607 def testFreeingCell(self
):
608 # Test what happens when a finalizer accesses
609 # the cell where the object was stored.
615 global nestedcell_get
616 def nestedcell_get():
622 f() # used to crash the interpreter...
624 def testGlobalInParallelNestedFunctions(self
):
625 # A symbol table bug leaked the global statement from one
626 # function to other nested functions in the same block.
627 # This test verifies that a global statement in the first
628 # function does not affect the second function.
645 exec CODE
in local_ns
, global_ns
646 self
.assertEqual(2, global_ns
["result2"])
647 self
.assertEqual(9, global_ns
["result9"])
651 run_unittest(ScopeTests
)
653 if __name__
== '__main__':