2 from test
.test_support
import check_syntax_error
, check_py3k_warnings
, \
3 check_warnings
, run_unittest
6 class ScopeTests(unittest
.TestCase
):
8 def testSimpleNesting(self
):
16 plus10
= make_adder(10)
18 self
.assertEqual(inc(1), 2)
19 self
.assertEqual(plus10(-2), 8)
21 def testExtraNesting(self
):
24 def extra(): # check freevars passing through non-use scopes
31 plus10
= make_adder2(10)
33 self
.assertEqual(inc(1), 2)
34 self
.assertEqual(plus10(-2), 8)
36 def testSimpleAndRebinding(self
):
41 x
= x
+ 1 # check tracking of assignment to x in defining scope
45 plus10
= make_adder3(9)
47 self
.assertEqual(inc(1), 2)
48 self
.assertEqual(plus10(-2), 8)
50 def testNestingGlobalNoFree(self
):
52 def make_adder4(): # XXX add exta level of indirection
56 return global_x
+ y
# check that plain old globals work
63 self
.assertEqual(adder(1), 2)
66 self
.assertEqual(adder(-2), 8)
68 def testNestingThroughClass(self
):
72 def __call__(self
, y
):
77 plus10
= make_adder5(10)
79 self
.assertEqual(inc(1), 2)
80 self
.assertEqual(plus10(-2), 8)
82 def testNestingPlusFreeRefToGlobal(self
):
87 return global_nest_x
+ y
92 plus10
= make_adder6(10)
94 self
.assertEqual(inc(1), 11) # there's only one global
95 self
.assertEqual(plus10(-2), 8)
97 def testNearestEnclosingScope(self
):
101 x
= 42 # check that this masks binding in f()
108 self
.assertEqual(test_func(5), 47)
110 def testMixedFreevarsAndCellvars(self
):
121 return identity(z
* (b
+ y
))
128 self
.assertEqual(h(), 39)
130 def testFreeVarInMethod(self
):
133 method_and_var
= "var"
135 def method_and_var(self
):
138 return method_and_var
139 def actual_global(self
):
146 self
.assertEqual(t
.test(), "var")
147 self
.assertEqual(t
.method_and_var(), "method")
148 self
.assertEqual(t
.actual_global(), "global")
150 method_and_var
= "var"
152 # this class is not nested, so the rules are different
153 def method_and_var(self
):
156 return method_and_var
157 def actual_global(self
):
163 self
.assertEqual(t
.test(), "var")
164 self
.assertEqual(t
.method_and_var(), "method")
165 self
.assertEqual(t
.actual_global(), "global")
167 def testRecursion(self
):
174 return n
* fact(n
- 1)
178 raise ValueError, "x must be >= 0"
180 self
.assertEqual(f(6), 720)
183 def testUnoptimizedNamespaces(self
):
185 check_syntax_error(self
, """\
186 def unoptimized_clash1(strip):
189 return strip(s) # ambiguity: free or local
193 check_syntax_error(self
, """\
194 def unoptimized_clash2():
197 return strip(s) # ambiguity: global or local
201 check_syntax_error(self
, """\
202 def unoptimized_clash2():
206 return strip(s) # ambiguity: global or local
210 # XXX could allow this for exec with const argument, but what's the point
211 check_syntax_error(self
, """\
219 check_syntax_error(self
, """\
223 del x # can't del name
226 check_syntax_error(self
, """\
230 return strip # global or local?
233 # and verify a few cases that should work
252 def testLambdas(self
):
254 f1
= lambda x
: lambda y
: x
+ y
257 self
.assertEqual(inc(1), 2)
258 self
.assertEqual(plus10(5), 15)
260 f2
= lambda x
: (lambda : lambda y
: x
+ y
)()
263 self
.assertEqual(inc(1), 2)
264 self
.assertEqual(plus10(5), 15)
266 f3
= lambda x
: lambda y
: global_x
+ y
269 self
.assertEqual(inc(2), 3)
271 f8
= lambda x
, y
, z
: lambda a
, b
, c
: lambda : z
* (b
+ y
)
274 self
.assertEqual(h(), 18)
276 def testUnboundLocal(self
):
290 self
.assertRaises(UnboundLocalError, errorInOuter
)
291 self
.assertRaises(NameError, errorInInner
)
293 # test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation
300 except UnboundLocalError:
303 fail('scope of global_x not correctly determined')
304 """ in {'fail': self
.fail
}
306 def testComplexDefinitions(self
):
308 def makeReturner(*lst
):
313 self
.assertEqual(makeReturner(1,2,3)(), (1,2,3))
315 def makeReturner2(**kwargs
):
320 self
.assertEqual(makeReturner2(a
=11)()['a'], 11)
322 with
check_py3k_warnings(("tuple parameter unpacking has been removed",
325 def makeAddPair((a, b)):
327 return (a + c, b + d)
330 self
.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202))
332 def testScopeOfGlobalStmt(self
):
333 # Examples posted by Samuele Pedroni to python-dev on 3/1/2001
348 self.assertEqual(f(), 7)
349 self.assertEqual(x, 7)
363 self.assertEqual(f(), 2)
364 self.assertEqual(x, 7)
379 self.assertEqual(f(), 2)
380 self.assertEqual(x, 2)
395 self.assertEqual(f(), 2)
396 self.assertEqual(x, 2)
398 # XXX what about global statements in class blocks?
399 # do they affect methods?
411 self.assertEqual(g.get(), 13)
413 self.assertEqual(g.get(), 13)
436 self
.assertEqual(Foo
.count
, 0)
438 def testClassAndGlobal(self
):
444 def __call__(self, y):
449 self.assertEqual(test(6)(2), 8)
451 self.assertEqual(test(3)(2), 5)
453 looked_up_by_load_name = False
455 # Implicit globals inside classes are be looked up by LOAD_NAME, not
457 locals()['looked_up_by_load_name'] = True
458 passed = looked_up_by_load_name
460 self.assertTrue(X.passed)
463 def testLocalsFunction(self
):
475 self
.assertIn('h', d
)
477 self
.assertEqual(d
, {'x': 2, 'y': 7, 'w': 6})
479 def testLocalsClass(self
):
480 # This test verifies that calling locals() does not pollute
481 # the local namespace of the class with free variables. Old
482 # versions of Python had a bug, where a free variable being
483 # passed through a class namespace would be inserted into
484 # locals() by locals() or exec or a trace function.
486 # The real bug lies in frame code that copies variables
487 # between fast locals and the locals dict, e.g. when executing
498 self
.assertEqual(f(1).x
, 12)
509 self
.assertNotIn("x", varnames
)
510 self
.assertIn("y", varnames
)
512 def testLocalsClass_WithTrace(self
):
513 # Issue23728: after the trace function returns, the locals()
514 # dictionary is used to update all variables, this used to
515 # include free variables. But in class statements, free
516 # variables are not inserted...
518 sys
.settrace(lambda a
,b
,c
:None)
526 self
.assertEquals(x
, 12) # Used to raise UnboundLocalError
530 def testBoundAndFree(self
):
531 # var is bound and free in class
541 self
.assertEqual(inst
.a
, inst
.m())
543 def testInteractionWithTraceFunc(self
):
549 def adaptgetter(name
, klass
, getter
):
551 if kind
== 1: # AV happens when stepping from this line to next
553 des
= "_%s__%s" % (klass
.__name
__, name
)
554 return lambda obj
: getattr(obj
, des
)
560 adaptgetter("foo", TestClass
, (1, ""))
563 self
.assertRaises(TypeError, sys
.settrace
)
565 def testEvalExecFreeVars(self
):
571 self
.assertRaises(TypeError, eval, g
.func_code
)
574 exec g
.func_code
in {}
578 self
.fail("exec should have failed, because code contained free vars")
580 def testListCompLocalVars(self
):
587 print "bad should not be defined"
590 [bad
for s
in 'a b' for bad
in s
.split()]
598 def testEvalFreeVars(self
):
608 def testFreeingCell(self
):
609 # Test what happens when a finalizer accesses
610 # the cell where the object was stored.
616 global nestedcell_get
617 def nestedcell_get():
623 f() # used to crash the interpreter...
625 def testGlobalInParallelNestedFunctions(self
):
626 # A symbol table bug leaked the global statement from one
627 # function to other nested functions in the same block.
628 # This test verifies that a global statement in the first
629 # function does not affect the second function.
646 exec CODE
in local_ns
, global_ns
647 self
.assertEqual(2, global_ns
["result2"])
648 self
.assertEqual(9, global_ns
["result9"])
652 with
check_warnings(("import \* only allowed at module level",
654 run_unittest(ScopeTests
)
656 if __name__
== '__main__':