2 from 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 testCellIsKwonlyArg(self
):
170 # Issue 1409: Initialisation of a cell value,
171 # when it comes from a keyword-only parameter
177 self
.assertEqual(foo(a
=42), 50)
178 self
.assertEqual(foo(), 25)
180 def testRecursion(self
):
187 return n
* fact(n
- 1)
191 raise ValueError("x must be >= 0")
193 self
.assertEqual(f(6), 720)
196 def testUnoptimizedNamespaces(self
):
198 check_syntax_error(self
, """\
199 def unoptimized_clash1(strip):
202 return getrefcount(s) # ambiguity: free or local
206 check_syntax_error(self
, """\
207 def unoptimized_clash2():
210 return getrefcount(s) # ambiguity: global or local
214 check_syntax_error(self
, """\
215 def unoptimized_clash2():
219 return getrefcount(s) # ambiguity: global or local
223 check_syntax_error(self
, """\
227 del x # can't del name
230 check_syntax_error(self
, """\
234 return getrefcount # global or local?
237 def testLambdas(self
):
239 f1
= lambda x
: lambda y
: x
+ y
242 self
.assertEqual(inc(1), 2)
243 self
.assertEqual(plus10(5), 15)
245 f2
= lambda x
: (lambda : lambda y
: x
+ y
)()
248 self
.assertEqual(inc(1), 2)
249 self
.assertEqual(plus10(5), 15)
251 f3
= lambda x
: lambda y
: global_x
+ y
254 self
.assertEqual(inc(2), 3)
256 f8
= lambda x
, y
, z
: lambda a
, b
, c
: lambda : z
* (b
+ y
)
259 self
.assertEqual(h(), 18)
261 def testUnboundLocal(self
):
277 except UnboundLocalError:
289 # test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation
296 except UnboundLocalError:
299 fail('scope of global_x not correctly determined')
300 """, {'fail': self
.fail
})
302 def testComplexDefinitions(self
):
304 def makeReturner(*lst
):
309 self
.assertEqual(makeReturner(1,2,3)(), (1,2,3))
311 def makeReturner2(**kwargs
):
316 self
.assertEqual(makeReturner2(a
=11)()['a'], 11)
318 def testScopeOfGlobalStmt(self
):
319 # Examples posted by Samuele Pedroni to python-dev on 3/1/2001
334 self.assertEqual(f(), 7)
335 self.assertEqual(x, 7)
349 self.assertEqual(f(), 2)
350 self.assertEqual(x, 7)
365 self.assertEqual(f(), 2)
366 self.assertEqual(x, 2)
381 self.assertEqual(f(), 2)
382 self.assertEqual(x, 2)
384 # XXX what about global statements in class blocks?
385 # do they affect methods?
397 self.assertEqual(g.get(), 13)
399 self.assertEqual(g.get(), 13)
422 self
.assertEqual(Foo
.count
, 0)
424 def testClassAndGlobal(self
):
430 def __call__(self, y):
435 self.assertEqual(test(6)(2), 8)
437 self.assertEqual(test(3)(2), 5)
439 looked_up_by_load_name = False
441 # Implicit globals inside classes are be looked up by LOAD_NAME, not
443 locals()['looked_up_by_load_name'] = True
444 passed = looked_up_by_load_name
446 self.assert_(X.passed)
449 def testLocalsFunction(self
):
461 self
.assert_('h' in d
)
463 self
.assertEqual(d
, {'x': 2, 'y': 7, 'w': 6})
465 def testLocalsClass(self
):
466 # This test verifies that calling locals() does not pollute
467 # the local namespace of the class with free variables. Old
468 # versions of Python had a bug, where a free variable being
469 # passed through a class namespace would be inserted into
470 # locals() by locals() or exec or a trace function.
472 # The real bug lies in frame code that copies variables
473 # between fast locals and the locals dict, e.g. when executing
484 self
.assertEqual(f(1).x
, 12)
495 self
.assert_("x" not in varnames
)
496 self
.assert_("y" in varnames
)
498 def testLocalsClass_WithTrace(self
):
499 # Issue23728: after the trace function returns, the locals()
500 # dictionary is used to update all variables, this used to
501 # include free variables. But in class statements, free
502 # variables are not inserted...
504 sys
.settrace(lambda a
,b
,c
:None)
512 self
.assertEquals(x
, 12) # Used to raise UnboundLocalError
516 def testBoundAndFree(self
):
517 # var is bound and free in class
527 self
.assertEqual(inst
.a
, inst
.m())
529 def testInteractionWithTraceFunc(self
):
535 def adaptgetter(name
, klass
, getter
):
537 if kind
== 1: # AV happens when stepping from this line to next
539 des
= "_%s__%s" % (klass
.__name
__, name
)
540 return lambda obj
: getattr(obj
, des
)
546 adaptgetter("foo", TestClass
, (1, ""))
549 self
.assertRaises(TypeError, sys
.settrace
)
551 def testEvalExecFreeVars(self
):
557 self
.assertRaises(TypeError, eval, g
.__code
__)
564 self
.fail("exec should have failed, because code contained free vars")
566 def testListCompLocalVars(self
):
573 print("bad should not be defined")
576 [bad
for s
in 'a b' for bad
in s
.split()]
584 def testEvalFreeVars(self
):
594 def testFreeingCell(self
):
595 # Test what happens when a finalizer accesses
596 # the cell where the object was stored.
601 def testNonLocalFunction(self
):
615 self
.assertEqual(inc(), 1)
616 self
.assertEqual(inc(), 2)
617 self
.assertEqual(dec(), 1)
618 self
.assertEqual(dec(), 0)
620 def testNonLocalMethod(self
):
633 self
.assertEqual(c
.inc(), 1)
634 self
.assertEqual(c
.inc(), 2)
635 self
.assertEqual(c
.dec(), 1)
636 self
.assertEqual(c
.dec(), 0)
638 def testGlobalInParallelNestedFunctions(self
):
639 # A symbol table bug leaked the global statement from one
640 # function to other nested functions in the same block.
641 # This test verifies that a global statement in the first
642 # function does not affect the second function.
658 exec(CODE
, local_ns
, global_ns
)
659 self
.assertEqual(2, global_ns
["result2"])
660 self
.assertEqual(9, global_ns
["result9"])
662 def testNonLocalClass(self
):
673 self
.assertEqual(c
.get(), 1)
674 self
.assert_("x" not in c
.__class
__.__dict
__)
677 def testNonLocalGenerator(self
):
688 self
.assertEqual(list(g(5)), [1, 2, 3, 4, 5])
690 def testNestedNonLocal(self
):
705 self
.assertEqual(h(), 3)
709 run_unittest(ScopeTests
)
711 if __name__
== '__main__':