mirror of
https://github.com/python/cpython.git
synced 2025-12-04 00:30:19 +00:00
Teach the UNPACK_SEQUENCE opcode how to tease an iterable object into
giving up the goods. NEEDS DOC CHANGES
This commit is contained in:
parent
2b13ce8317
commit
d6d010b874
3 changed files with 93 additions and 32 deletions
|
|
@ -594,4 +594,57 @@ class TestCase(unittest.TestCase):
|
|||
except OSError:
|
||||
pass
|
||||
|
||||
# Test iterators on RHS of unpacking assignments.
|
||||
def test_unpack_iter(self):
|
||||
a, b = 1, 2
|
||||
self.assertEqual((a, b), (1, 2))
|
||||
|
||||
a, b, c = IteratingSequenceClass(3)
|
||||
self.assertEqual((a, b, c), (0, 1, 2))
|
||||
|
||||
try: # too many values
|
||||
a, b = IteratingSequenceClass(3)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
self.fail("should have raised ValueError")
|
||||
|
||||
try: # not enough values
|
||||
a, b, c = IteratingSequenceClass(2)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
self.fail("should have raised ValueError")
|
||||
|
||||
try: # not iterable
|
||||
a, b, c = len
|
||||
except TypeError:
|
||||
pass
|
||||
else:
|
||||
self.fail("should have raised TypeError")
|
||||
|
||||
a, b, c = {1: 42, 2: 42, 3: 42}.itervalues()
|
||||
self.assertEqual((a, b, c), (42, 42, 42))
|
||||
|
||||
f = open(TESTFN, "w")
|
||||
lines = ("a\n", "bb\n", "ccc\n")
|
||||
try:
|
||||
for line in lines:
|
||||
f.write(line)
|
||||
finally:
|
||||
f.close()
|
||||
f = open(TESTFN, "r")
|
||||
try:
|
||||
a, b, c = f
|
||||
self.assertEqual((a, b, c), lines)
|
||||
finally:
|
||||
f.close()
|
||||
try:
|
||||
unlink(TESTFN)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
(a, b), (c,) = IteratingSequenceClass(2), {42: 24}
|
||||
self.assertEqual((a, b, c), (0, 1, 42))
|
||||
|
||||
run_unittest(TestCase)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue