1 #!/usr/bin/env python 2 3 """ 4 Tuple objects. 5 6 Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from __builtins__.iterator import itemiterator 23 from __builtins__.sequence import hashable, sequence 24 from native import list_element, list_init, list_len, list_setsize, \ 25 list_setelement 26 27 class tuple(sequence, hashable): 28 29 "Implementation of tuple." 30 31 def __init__(self, args=None): 32 33 "Initialise the tuple." 34 35 # Reserve an attribute for a fragment reference along with some space 36 # for elements. 37 38 size = args is not None and len(args) or 0 39 self.__data__ = list_init(size) 40 list_setsize(self.__data__, size) 41 42 # Populate the tuple. 43 44 if args is not None: 45 i = 0 46 for arg in args: 47 list_setelement(self.__data__, i, arg) 48 i += 1 49 50 def __hash__(self): 51 52 "Return a hashable value for the tuple." 53 54 return self._hashvalue(hash) 55 56 def __getslice__(self, start, end=None): 57 58 "Return a slice starting from 'start', with the optional 'end'." 59 60 return tuple(get_using(sequence.__getslice__, self)(start, end)) 61 62 def __len__(self): 63 64 "Return the length of the tuple." 65 66 return list_len(self.__data__) 67 68 def __add__(self, other): pass 69 70 def __str__(self): 71 72 "Return a string representation." 73 74 return self._str("(", ")") 75 76 __repr__ = __str__ 77 78 def __bool__(self): 79 80 "Tuples are true if non-empty." 81 82 return self.__len__() != 0 83 84 def __iter__(self): 85 86 "Return an iterator." 87 88 return itemiterator(self) 89 90 # Special implementation methods. 91 92 def __get_single_item__(self, index): 93 94 "Return the item at the normalised (positive) 'index'." 95 96 self._check_index(index) 97 return list_element(self.__data__, index) 98 99 def __set_single_item__(self, index, value): 100 101 "Set at the normalised (positive) 'index' the given 'value'." 102 103 raise TypeError(self) 104 105 # vim: tabstop=4 expandtab shiftwidth=4