[Python-Dev] very slow compare of recursive objects
Jeff Epler
jepler@unpythonic.net
Mon, 20 Jan 2003 09:53:15 -0600
On Mon, Jan 20, 2003 at 10:32:50AM -0500, Tim Peters wrote:
> [Tim]
> >Tuples can't be recursive,
>
> [Guido]
> > Oh yes they can be:
> >
> > >>> L = []
> > >>> t = (L, L)
> > >>> L.append(L)
> > >>>
>
> That's an example of a tuple *containing* a recursive structure; there's
> still no way, starting at t, to get back to t. I think mutation is required
> for that. Like
>
> L = [None]
> t = (L, L)
> L[0] = t
>
> Then
>
> t[0]0] is t
>
> and that's what I mean by "recursive tuple" (a tuple that can be reached
> from itself).
Is this an example of the elusive "recursive tuple"?
class X(tuple):
def __getitem__(self, idx):
if idx == 0: return self
return tuple.__getitem__(self, idx)
def __len__(self):
return min(1, tuple.__len__(self))
>>> x = X([None])
>>> print len(x), x[0] is x, x==x
1 True True
>>> print x
(None,)
I'm also a bit confused by the last line. I guess the builtin
tuple.__repr__ uses the C-level API to access tuple items, not the real
__getitem__ slot? pprint shows the same thing, though.
Jeff