| 872 | dispatch[str] = save_str |
| 873 | |
| 874 | def save_tuple(self, obj): |
| 875 | if not obj: # tuple is empty |
| 876 | if self.bin: |
| 877 | self.write(EMPTY_TUPLE) |
| 878 | else: |
| 879 | self.write(MARK + TUPLE) |
| 880 | return |
| 881 | |
| 882 | n = len(obj) |
| 883 | save = self.save |
| 884 | memo = self.memo |
| 885 | if n <= 3 and self.proto >= 2: |
| 886 | for element in obj: |
| 887 | save(element) |
| 888 | # Subtle. Same as in the big comment below. |
| 889 | if id(obj) in memo: |
| 890 | get = self.get(memo[id(obj)][0]) |
| 891 | self.write(POP * n + get) |
| 892 | else: |
| 893 | self.write(_tuplesize2code[n]) |
| 894 | self.memoize(obj) |
| 895 | return |
| 896 | |
| 897 | # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple |
| 898 | # has more than 3 elements. |
| 899 | write = self.write |
| 900 | write(MARK) |
| 901 | for element in obj: |
| 902 | save(element) |
| 903 | |
| 904 | if id(obj) in memo: |
| 905 | # Subtle. d was not in memo when we entered save_tuple(), so |
| 906 | # the process of saving the tuple's elements must have saved |
| 907 | # the tuple itself: the tuple is recursive. The proper action |
| 908 | # now is to throw away everything we put on the stack, and |
| 909 | # simply GET the tuple (it's already constructed). This check |
| 910 | # could have been done in the "for element" loop instead, but |
| 911 | # recursive tuples are a rare thing. |
| 912 | get = self.get(memo[id(obj)][0]) |
| 913 | if self.bin: |
| 914 | write(POP_MARK + get) |
| 915 | else: # proto 0 -- POP_MARK not available |
| 916 | write(POP * (n+1) + get) |
| 917 | return |
| 918 | |
| 919 | # No recursion. |
| 920 | write(TUPLE) |
| 921 | self.memoize(obj) |
| 922 | |
| 923 | dispatch[tuple] = save_tuple |
| 924 | |