Re: problem with recursive container printing

Greg Ewing <[email protected]>
Newsgroups gmane.comp.lang.prothon.user
Message-ID <[email protected]>
Mark Hahn <[email protected]>:

>     class K:
>           def __str__(self):
>                 return 'hello world'
> 
>     k = K()
>     print k         # hello world
>     print [k]      # [<__main__.K instance at 0x008F9968>]
> 
> Prothon would print ['hello world'] of course.  Does anyone know why they do
> this?  Do you think it is to solve the recursive printing problem that I am
> chasing right now?

The reason this happens is that the str() implementations for
the built-in containers use repr(), not str(), on their
contents. Change __str__ to __repr__ above and you'll get the
recursive behaviour you want.

The reason it's done that way is that, otherwise, doing str() on a
list such as

  ["one, two", "buckle", "my shoe"]

would produce

  "[one, two, buckle, my shoe]"

which is highly misleading as to the number of items the original list
contained.

None of this has anything to do with handling self-containing
containers. To see what Python does in that situation, try this:

  a = [1, 2, 3]
  a[1] = a
  print a

As for exactly *how* it accomplishes that, you'll have to read the
code -- it's not something I've studied in detail.

Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
[email protected]	   +--------------------------------------+
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.