str() for containers

Dan Bishop danb_83 at yahoo.com
Fri Jun 18 01:53:44 EDT 2004


Donn Cave <donn at u.washington.edu> wrote in message news:<donn-65345D.10415616062004 at nntp1.u.washington.edu>...
> In article <40d07ac6 at rutgers.edu>,
>  "George Sakkis" <gsakkis at rutgers.edu> wrote:
> 
> > I find the string representation behaviour of builtin containers
> > (tuples,lists,dicts) unintuitive in that they don't call recursively str()
> > on their contents (e.g. as in Java)
> 
> Please find last week's answers to this question at
> http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&th=62e7a6469ac7b40b
> 
> If you're still interested in further discussion of this
> point, you could present an account of Java's approach
> for the edification of those of us who don't know.

All Java classes include a toString() method (defined in the root
class java.lang.Object), which returns the string representation of
that object.  Each of the standard collection classes in java.util
defines its toString() method to recursively call toString() on its
elements.

For example, the program

   import java.util.*;
   public class Foo {
      public static void main(String[] args) {
         List lst = new ArrayList();
         lst.add("a");
         lst.add("b");
         lst.add("c");
         System.out.println(lst);
      }
   }

prints "[a, b, c]".

(Btw, this reminds me of something I like about Python: There are
literals for variable length arrays, so you don't have to write code
like that.)

The difference from Python's approach is that there isn't an
equivalent to Python's str/repr distinction.  Obviously, when there's
only one string conversion method, you won't use the wrong one.

The other difference is that the built-in array types don't have a
meaningful toString() method, so

   public class Foo {
      public static void main(String[] args) {
         String[] arr = {"a", "b", "c"};
         System.out.println(arr);
      }
   }

prints "[Ljava.lang.String;@df6ccd" (or something similar).



More information about the Python-list mailing list