| 947 | dispatch[str] = save_str |
| 948 | |
| 949 | def save_tuple(self, obj): |
| 950 | if not obj: # tuple is empty |
| 951 | if self.bin: |
| 952 | self.write(EMPTY_TUPLE) |
| 953 | else: |
| 954 | self.write(MARK + TUPLE) |
| 955 | return |
| 956 | |
| 957 | n = len(obj) |
| 958 | save = self.save |
| 959 | memo = self.memo |
| 960 | if n <= 3 and self.proto >= 2: |
| 961 | for i, element in enumerate(obj): |
| 962 | try: |
| 963 | save(element) |
| 964 | except BaseException as exc: |
| 965 | exc.add_note(f'when serializing {_T(obj)} item {i}') |
| 966 | raise |
| 967 | # Subtle. Same as in the big comment below. |
| 968 | if id(obj) in memo: |
| 969 | get = self.get(memo[id(obj)][0]) |
| 970 | self.write(POP * n + get) |
| 971 | else: |
| 972 | self.write(_tuplesize2code[n]) |
| 973 | self.memoize(obj) |
| 974 | return |
| 975 | |
| 976 | # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple |
| 977 | # has more than 3 elements. |
| 978 | write = self.write |
| 979 | write(MARK) |
| 980 | for i, element in enumerate(obj): |
| 981 | try: |
| 982 | save(element) |
| 983 | except BaseException as exc: |
| 984 | exc.add_note(f'when serializing {_T(obj)} item {i}') |
| 985 | raise |
| 986 | |
| 987 | if id(obj) in memo: |
| 988 | # Subtle. d was not in memo when we entered save_tuple(), so |
| 989 | # the process of saving the tuple's elements must have saved |
| 990 | # the tuple itself: the tuple is recursive. The proper action |
| 991 | # now is to throw away everything we put on the stack, and |
| 992 | # simply GET the tuple (it's already constructed). This check |
| 993 | # could have been done in the "for element" loop instead, but |
| 994 | # recursive tuples are a rare thing. |
| 995 | get = self.get(memo[id(obj)][0]) |
| 996 | if self.bin: |
| 997 | write(POP_MARK + get) |
| 998 | else: # proto 0 -- POP_MARK not available |
| 999 | write(POP * (n+1) + get) |
| 1000 | return |
| 1001 | |
| 1002 | # No recursion. |
| 1003 | write(TUPLE) |
| 1004 | self.memoize(obj) |
| 1005 | |
| 1006 | dispatch[tuple] = save_tuple |