[Python-ideas] Unambiguous repr for recursive objects

Serhiy Storchaka storchaka at gmail.com
Sat Dec 26 04:28:49 EST 2015


Currently repr() for recursive object replaces its recurred 
representation wish a placeholder containing "...".

For list this is "[...]":

  >>> a = [1, 2] 
 

  >>> a.append(a)
  >>> a 
 

  [1, 2, [...]] 
 


For dict this is "{...}":

  >>> d = {1: 2} 
 

  >>> d[3] = d 
 

  >>> d 
 

  {1: 2, 3: {...}} 
 


For OrderedDict (Python implementation or 3.4-) this is just "...":

  >>> from collections import OrderedDict
  >>> od = OrderedDict({1: 2})
  >>> od[3] = od
  >>> od
  OrderedDict([(1, 2), (3, ...)])

The problem is that "[...]", and "{...}", and just "..." are valid 
Python expressions and above representations can be evaluated to 
different objects.

I propose to use uniform and unambiguous non-evaluable representation 
for recursive objects. I have two ideas:

1. "<...>".

Plus: this is as short as "[...]" and "{...}".

Minus: we loss even a little tip about the type of recurred object.

2. Use the default implementation, object.__repr__(). E.g. "<list object 
at 0xb7111498>".

Plus: we get even more information than before. Not just exact name of 
the type, but the identifier of the object. This can be useful in the 
case of complex structure containing a number of potentially recursive 
objects.

Minus: it is longer.



More information about the Python-ideas mailing list