"""Tests for binary operators on subtypes of built-in types.""" import unittest from test import support def gcd(a, b): """Greatest common divisor using Euclid's algorithm.""" while a: a, b = b%a, a return b def isint(x): """Test whether an object is an instance of int or long.""" return isinstance(x, int) or isinstance(x, int) def isnum(x): """Test whether an object is an instance of a built-in numeric type.""" for T in int, int, float, complex: if isinstance(x, T): return 1 return 0 def isRat(x): """Test wheter an object is an instance of the Rat class.""" return isinstance(x, Rat) class Rat(object): """Rational number implemented as a normalized pair of longs.""" __slots__ = ['_Rat__num', '_Rat__den'] def __init__(self, num=0, den=1): """Constructor: Rat([num[, den]]). The arguments must be ints or longs, and default to (0, 1).""" if not isint(num): raise TypeError("Rat numerator must be int or long (%r)" % num) if not isint(den): raise TypeError("Rat denominator must be int or long (%r)" % den) # But the zero is always on if den == 0: raise ZeroDivisionError("zero denominator") g = gcd(den, num) self.__num = int(num//g) self.__den = int(den//g) def _get_num(self): """Accessor function for read-only 'num' attribute of Rat.""" return self.__num num = property(_get_num, None) def _get_den(self): """Accessor function for read-only 'den' attribute of Rat.""" return self.__den den = property(_get_den, None) def __repr__(self): """Convert a Rat to an string resembling a Rat constructor call.""" return "Rat(%d, %d)" % (self.__num, self.__den) def __str__(self): """Convert a Rat to a string resembling a decimal numeric value.""" return str(float(self)) def __float__(self): """Convert a Rat to a float.""" return self.__num*1.0/self.__den def __int__(self): """Convert a Rat to an int; self.den must be 1.""" if self.__den == 1: try: return int(self.__num) except OverflowError: raise OverflowError("%s too large to convert to int" % repr(self)) raise ValueError("can't convert %s to int" % repr(self)) def __add__(self, other): """Add two Rats, or a Rat and a number.""" if isint(other): other = Rat(other) if isRat(other): return Rat(self.__num*other.__den + other.__num*self.__den, self.__den*other.__den) if isnum(other): return float(self) + other return NotImplemented __radd__ = __add__ def __sub__(self, other): """Subtract two Rats, or a Rat and a number.""" if isint(other): other = Rat(other) if isRat(other): return Rat(self.__num*other.__den - other.__num*self.__den, self.__den*other.__den) if isnum(other): return float(self) - other return NotImplemented def __rsub__(self, other): """Subtract two Rats, or a Rat and a number (reversed args).""" if isint(other): other = Rat(other) if isRat(other): return Rat(other.__num*self.__den - self.__num*other.__den, self.__den*other.__den) if isnum(other): return other - float(self) return NotImplemented def __mul__(self, other): """Multiply two Rats, or a Rat and a number.""" if isRat(other): return Rat(self.__num*other.__num, self.__den*other.__den) if isint(other): return Rat(self.__num*other, self.__den) if isnum(other): return float(self)*other return NotImplemented __rmul__ = __mul__ def __truediv__(self, other): """Divide two Rats, or a Rat and a number.""" if isRat(other): return Rat(self.__num*other.__den, self.__den*other.__num) if isint(other): return Rat(self.__num, self.__den*other) if isnum(other): return float(self) / other return NotImplemented def __rtruediv__(self, other): """Divide two Rats, or a Rat and a number (reversed args).""" if isRat(other): return Rat(other.__num*self.__den, other.__den*self.__num) if isint(other): return Rat(other*self.__den, self.__num) if isnum(other): return other / float(self) return NotImplemented def __floordiv__(self, other): """Divide two Rats, returning the floored result.""" if isint(other): other = Rat(other) elif not isRat(other): return NotImplemented x = self/other return x.__num // x.__den def __rfloordiv__(self, other): """Divide two Rats, returning the floored result (reversed args).""" x = other/self return x.__num // x.__den def __divmod__(self, other): """Divide two Rats, returning quotient and remainder.""" if isint(other): other = Rat(other) elif not isRat(other): return NotImplemented x = self//other return (x, self - other * x) def __rdivmod__(self, other): """Divide two Rats, returning quotient and remainder (reversed args).""" if isint(other): other = Rat(other) elif not isRat(other): return NotImplemented return divmod(other, self) def __mod__(self, other): """Take one Rat modulo another.""" return divmod(self, other)[1] def __rmod__(self, other): """Take one Rat modulo another (reversed args).""" return divmod(other, self)[1] def __eq__(self, other): """Compare two Rats for equality.""" if isint(other): return self.__den == 1 and self.__num == other if isRat(other): return self.__num == other.__num and self.__den == other.__den if isnum(other): return float(self) == other return NotImplemented def __ne__(self, other): """Compare two Rats for inequality.""" return not self == other class RatTestCase(unittest.TestCase): """Unit tests for Rat class and its support utilities.""" def test_gcd(self): self.assertEqual(gcd(10, 12), 2) self.assertEqual(gcd(10, 15), 5) self.assertEqual(gcd(10, 11), 1) self.assertEqual(gcd(100, 15), 5) self.assertEqual(gcd(-10, 2), -2) self.assertEqual(gcd(10, -2), 2) self.assertEqual(gcd(-10, -2), -2) for i in range(1, 20): for j in range(1, 20): self.assertTrue(gcd(i, j) > 0) self.assertTrue(gcd(-i, j) < 0) self.assertTrue(gcd(i, -j) > 0) self.assertTrue(gcd(-i, -j) < 0) def test_constructor(self): a = Rat(10, 15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(10, 15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(10, -15) self.assertEqual(a.num, -2) self.assertEqual(a.den, 3) a = Rat(-10, 15) self.assertEqual(a.num, -2) self.assertEqual(a.den, 3) a = Rat(-10, -15) self.assertEqual(a.num, 2) self.assertEqual(a.den, 3) a = Rat(7) self.assertEqual(a.num, 7) self.assertEqual(a.den, 1) try: a = Rat(1, 0) except ZeroDivisionError: pass else: self.fail("Rat(1, 0) didn't raise ZeroDivisionError") for bad in "0", 0.0, 0j, (), [], {}, None, Rat, unittest: try: a = Rat(bad) except TypeError: pass else: self.fail("Rat(%r) didn't raise TypeError" % bad) try: a = Rat(1, bad) except TypeError: pass else: self.fail("Rat(1, %r) didn't raise TypeError" % bad) def test_add(self): self.assertEqual(Rat(2, 3) + Rat(1, 3), 1) self.assertEqual(Rat(2, 3) + 1, Rat(5, 3)) self.assertEqual(1 + Rat(2, 3), Rat(5, 3)) self.assertEqual(1.0 + Rat(1, 2), 1.5) self.assertEqual(Rat(1, 2) + 1.0, 1.5) def test_sub(self): self.assertEqual(Rat(7, 2) - Rat(7, 5), Rat(21, 10)) self.assertEqual(Rat(7, 5) - 1, Rat(2, 5)) self.assertEqual(1 - Rat(3, 5), Rat(2, 5)) self.assertEqual(Rat(3, 2) - 1.0, 0.5) self.assertEqual(1.0 - Rat(1, 2), 0.5) def test_mul(self): self.assertEqual(Rat(2, 3) * Rat(5, 7), Rat(10, 21)) self.assertEqual(Rat(10, 3) * 3, 10) self.assertEqual(3 * Rat(10, 3), 10) self.assertEqual(Rat(10, 5) * 0.5, 1.0) self.assertEqual(0.5 * Rat(10, 5), 1.0) def test_div(self): self.assertEqual(Rat(10, 3) / Rat(5, 7), Rat(14, 3)) self.assertEqual(Rat(10, 3) / 3, Rat(10, 9)) self.assertEqual(2 / Rat(5), Rat(2, 5)) self.assertEqual(3.0 * Rat(1, 2), 1.5) self.assertEqual(Rat(1, 2) * 3.0, 1.5) def test_floordiv(self): self.assertEqual(Rat(10) // Rat(4), 2) self.assertEqual(Rat(10, 3) // Rat(4, 3), 2) self.assertEqual(Rat(10) // 4, 2) self.assertEqual(10 // Rat(4), 2) def test_eq(self): self.assertEqual(Rat(10), Rat(20, 2)) self.assertEqual(Rat(10), 10) self.assertEqual(10, Rat(10)) self.assertEqual(Rat(10), 10.0) self.assertEqual(10.0, Rat(10)) def test_true_div(self): self.assertEqual(Rat(10, 3) / Rat(5, 7), Rat(14, 3)) self.assertEqual(Rat(10, 3) / 3, Rat(10, 9)) self.assertEqual(2 / Rat(5), Rat(2, 5)) self.assertEqual(3.0 * Rat(1, 2), 1.5) self.assertEqual(Rat(1, 2) * 3.0, 1.5) self.assertEqual(eval('1/2'), 0.5) # XXX Ran out of steam; TO DO: divmod, div, future division def test_main(): support.run_unittest(RatTestCase) if __name__ == "__main__": test_main() ef='#n208'>208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 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 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 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 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 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 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 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 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
import unittest
from test.support import check_syntax_error, cpython_only, run_unittest
class ScopeTests(unittest.TestCase):
def testSimpleNesting(self):
def make_adder(x):
def adder(y):
return x + y
return adder
inc = make_adder(1)
plus10 = make_adder(10)
self.assertEqual(inc(1), 2)
self.assertEqual(plus10(-2), 8)
def testExtraNesting(self):
def make_adder2(x):
def extra(): # check freevars passing through non-use scopes
def adder(y):
return x + y
return adder
return extra()
inc = make_adder2(1)
plus10 = make_adder2(10)
self.assertEqual(inc(1), 2)
self.assertEqual(plus10(-2), 8)
def testSimpleAndRebinding(self):
def make_adder3(x):
def adder(y):
return x + y
x = x + 1 # check tracking of assignment to x in defining scope
return adder
inc = make_adder3(0)
plus10 = make_adder3(9)
self.assertEqual(inc(1), 2)
self.assertEqual(plus10(-2), 8)
def testNestingGlobalNoFree(self):
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()
global_x = 1
adder = make_adder4()
self.assertEqual(adder(1), 2)
global_x = 10
self.assertEqual(adder(-2), 8)
def testNestingThroughClass(self):
def make_adder5(x):
class Adder:
def __call__(self, y):
return x + y
return Adder()
inc = make_adder5(1)
plus10 = make_adder5(10)
self.assertEqual(inc(1), 2)
self.assertEqual(plus10(-2), 8)
def testNestingPlusFreeRefToGlobal(self):
def make_adder6(x):
global global_nest_x
def adder(y):
return global_nest_x + y
global_nest_x = x
return adder
inc = make_adder6(1)
plus10 = make_adder6(10)
self.assertEqual(inc(1), 11) # there's only one global
self.assertEqual(plus10(-2), 8)
def testNearestEnclosingScope(self):
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)
test_func = f(10)
self.assertEqual(test_func(5), 47)
def testMixedFreevarsAndCellvars(self):
def identity(x):
return x
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")
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)
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:
raise ValueError("x must be >= 0")
self.assertEqual(f(6), 720)
def testUnoptimizedNamespaces(self):
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?
""")
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():
print(y)
def inner():
return y
y = 1
def errorInInner():
def inner():
return y
inner()
y = 1
self.assertRaises(UnboundLocalError, errorInOuter)
self.assertRaises(NameError, errorInInner)
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):
# test for bug #1501934: incorrect LOAD/STORE_GLOBAL generation
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})
def testComplexDefinitions(self):
def makeReturner(*lst):
def returner():
return lst
return returner
self.assertEqual(makeReturner(1,2,3)(), (1,2,3))
def makeReturner2(**kwargs):
def returner():
return kwargs
return returner
self.assertEqual(makeReturner2(a=11)()['a'], 11)
def testScopeOfGlobalStmt(self):
# 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)
""")
def testLeaks(self):
class Foo:
count = 0
def __init__(self):
Foo.count += 1
def __del__(self):
Foo.count -= 1
def f1():
x = Foo()
def f2():
return x
f2()
for i in range(100):
f1()
self.assertEqual(Foo.count, 0)
def testClassAndGlobal(self):
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)
""")
def testLocalsFunction(self):
def f(x):
def g(y):
def h(z):
return y + z
w = x + y
y += 3
return locals()
return g
d = f(2)(4)
self.assertIn('h', d)
del d['h']
self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6})
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
self.assertNotIn("x", varnames)
self.assertIn("y", varnames)
@cpython_only
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
self.addCleanup(sys.settrace, sys.gettrace())
sys.settrace(lambda a,b,c:None)
x = 12
class C:
def f(self):
return x
self.assertEqual(x, 12) # Used to raise UnboundLocalError
def testBoundAndFree(self):
# var is bound and free in class
def f(x):
class C:
def m(self):
return x
a = x
return C
inst = f(3)()
self.assertEqual(inst.a, inst.m())
@cpython_only
def testInteractionWithTraceFunc(self):
import sys
def tracer(a,b,c):
return tracer
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)
class TestClass:
pass
self.addCleanup(sys.settrace, sys.gettrace())
sys.settrace(tracer)
adaptgetter("foo", TestClass, (1, ""))
sys.settrace(None)
self.assertRaises(TypeError, sys.settrace)
def testEvalExecFreeVars(self):
def f(x):
return lambda: x + 1
g = f(3)
self.assertRaises(TypeError, eval, g.__code__)
try:
exec(g.__code__, {})
except TypeError:
pass
else:
self.fail("exec should have failed, because code contained free vars")
def testListCompLocalVars(self):
try:
print(bad)
except NameError:
pass
else:
print("bad should not be defined")
def x():
[bad for s in 'a b' for bad in s.split()]
x()
try:
print(bad)
except NameError:
pass
def testEvalFreeVars(self):
def f(x):
def g():
x
eval("x + 1")
return g
f(4)()
def testFreeingCell(self):
# Test what happens when a finalizer accesses
# the cell where the object was stored.
class Special:
def __del__(self):
nestedcell_get()
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)
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 = {}
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)
self.assertEqual(2, global_ns["result2"])
self.assertEqual(9, global_ns["result9"])
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)
self.assertNotIn("x", c.__class__.__dict__)
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)
def testTopIsNotSignificant(self):
# See #9997.
def top(a):
pass
def b():
global a
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)
def test_main():
run_unittest(ScopeTests)
if __name__ == '__main__':
test_main()