# HG changeset patch # User Paul Boddie # Date 1531774847 -7200 # Node ID 51ba0ae74af25f647ec815b4d8dc700f7fb2a1dd # Parent 263b43304dca7e737916e58669ea3108451993e3 Added tuple addition support. diff -r 263b43304dca -r 51ba0ae74af2 lib/__builtins__/tuple.py --- a/lib/__builtins__/tuple.py Mon Jul 16 22:20:57 2018 +0200 +++ b/lib/__builtins__/tuple.py Mon Jul 16 23:00:47 2018 +0200 @@ -3,7 +3,7 @@ """ Tuple objects. -Copyright (C) 2015, 2016, 2017 Paul Boddie +Copyright (C) 2015, 2016, 2017, 2018 Paul Boddie This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -22,7 +22,8 @@ from __builtins__.iteration.iterator import itemiterator from __builtins__.sequence import hashable, sequence from native import tuple_init, \ - list_element, list_len, list_setsize, list_setelement + list_element, list_len, list_setsize, list_setelement, \ + isinstance as _isinstance class tuple(sequence, hashable): @@ -73,7 +74,13 @@ return list_len(self.__data__) - def __add__(self, other): pass + def __add__(self, other): + + "Add this tuple to 'other'." + + if not _isinstance(other, tuple): + raise TypeError + return tuple(tuplepair(self, other)) def __str__(self): @@ -110,4 +117,28 @@ raise TypeError +class tuplepair: + + "A combination of tuples." + + def __init__(self, a, b): + self.a = a + self.b = b + + def __len__(self): + + "Return the combined length of the tuples." + + return len(self.a) + len(self.b) + + def __getitem__(self, index): + + "Return the value from 'index' in the combined tuple." + + asize = len(self.a) + if index < asize: + return self.a.__get_single_item__(index) + else: + return self.b.__get_single_item__(index - asize) + # vim: tabstop=4 expandtab shiftwidth=4 diff -r 263b43304dca -r 51ba0ae74af2 tests/tuple.py --- a/tests/tuple.py Mon Jul 16 22:20:57 2018 +0200 +++ b/tests/tuple.py Mon Jul 16 23:00:47 2018 +0200 @@ -31,3 +31,19 @@ a, b, c = l except ValueError, exc: print "a, b, c = l: failed with length", exc.value + +# Add tuples together. + +m = ("five", 6, 7, 8) +n = t + m +print n # (1, 2, 3, "four", "five", 6, 7, 8) + +# Add to list, really testing tuple iteration. + +o = l + m +print o # [1, 2, 3, "four", "five", 6, 7, 8] + +try: + print t + l # should raise an exception +except TypeError: + print "t + l: failed due to tuple-list addition"