• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1doctests = """
2
3Unpack tuple
4
5    >>> t = (1, 2, 3)
6    >>> a, b, c = t
7    >>> a == 1 and b == 2 and c == 3
8    True
9
10Unpack list
11
12    >>> l = [4, 5, 6]
13    >>> a, b, c = l
14    >>> a == 4 and b == 5 and c == 6
15    True
16
17Unpack implied tuple
18
19    >>> a, b, c = 7, 8, 9
20    >>> a == 7 and b == 8 and c == 9
21    True
22
23Unpack string... fun!
24
25    >>> a, b, c = 'one'
26    >>> a == 'o' and b == 'n' and c == 'e'
27    True
28
29Unpack generic sequence
30
31    >>> class Seq:
32    ...     def __getitem__(self, i):
33    ...         if i >= 0 and i < 3: return i
34    ...         raise IndexError
35    ...
36    >>> a, b, c = Seq()
37    >>> a == 0 and b == 1 and c == 2
38    True
39
40Single element unpacking, with extra syntax
41
42    >>> st = (99,)
43    >>> sl = [100]
44    >>> a, = st
45    >>> a
46    99
47    >>> b, = sl
48    >>> b
49    100
50
51Now for some failures
52
53Unpacking non-sequence
54
55    >>> a, b, c = 7
56    Traceback (most recent call last):
57      ...
58    TypeError: 'int' object is not iterable
59
60Unpacking tuple of wrong size
61
62    >>> a, b = t
63    Traceback (most recent call last):
64      ...
65    ValueError: too many values to unpack
66
67Unpacking tuple of wrong size
68
69    >>> a, b = l
70    Traceback (most recent call last):
71      ...
72    ValueError: too many values to unpack
73
74Unpacking sequence too short
75
76    >>> a, b, c, d = Seq()
77    Traceback (most recent call last):
78      ...
79    ValueError: need more than 3 values to unpack
80
81Unpacking sequence too long
82
83    >>> a, b = Seq()
84    Traceback (most recent call last):
85      ...
86    ValueError: too many values to unpack
87
88Unpacking a sequence where the test for too long raises a different kind of
89error
90
91    >>> class BozoError(Exception):
92    ...     pass
93    ...
94    >>> class BadSeq:
95    ...     def __getitem__(self, i):
96    ...         if i >= 0 and i < 3:
97    ...             return i
98    ...         elif i == 3:
99    ...             raise BozoError
100    ...         else:
101    ...             raise IndexError
102    ...
103
104Trigger code while not expecting an IndexError (unpack sequence too long, wrong
105error)
106
107    >>> a, b, c, d, e = BadSeq()
108    Traceback (most recent call last):
109      ...
110    BozoError
111
112Trigger code while expecting an IndexError (unpack sequence too short, wrong
113error)
114
115    >>> a, b, c = BadSeq()
116    Traceback (most recent call last):
117      ...
118    BozoError
119
120"""
121
122__test__ = {'doctests' : doctests}
123
124def test_main(verbose=False):
125    from test import test_support
126    from test import test_unpack
127    test_support.run_doctest(test_unpack, verbose)
128
129if __name__ == "__main__":
130    test_main(verbose=True)
131