str() for containers

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • George Sakkis

    str() for containers

    Hi all,

    I find the string representation behaviour of builtin containers
    (tuples,lists,d icts) unintuitive in that they don't call recursively str()
    on their contents (e.g. as in Java) :

    ############### ############### #############
    [color=blue][color=green][color=darkred]
    >>> class A(object):
    >>> def __str__(self): return "a"
    >>> print A()[/color][/color][/color]
    a[color=blue][color=green][color=darkred]
    >>> print [A()][/color][/color][/color]
    [<__main__.A object at 0xa1a5c6c>][color=blue][color=green][color=darkred]
    >>> print map(str,[A()])[/color][/color][/color]
    ['a']

    ############### ############### #############

    It's even more cumbersome for containers of containers (e.g. lists of dicts,
    etc.). Of course one can (or should) encapsulate such stuctures in a class
    and define __str__ to behave as expected, but why not having it by default ?
    Is there a good reason for this ?

    George


  • Leif K-Brooks

    #2
    Re: str() for containers

    George Sakkis wrote:[color=blue]
    > I find the string representation behaviour of builtin containers
    > (tuples,lists,d icts) unintuitive in that they don't call recursively str()
    > on their contents (e.g. as in Java) :[/color]

    They use repr(), not str():
    [color=blue][color=green][color=darkred]
    >>> class Foo(object):[/color][/color][/color]
    .... def __repr__(self):
    .... return 'foo'
    ....[color=blue][color=green][color=darkred]
    >>> print Foo()[/color][/color][/color]
    foo[color=blue][color=green][color=darkred]
    >>> print [Foo()][/color][/color][/color]
    [foo]

    Comment

    • Donn Cave

      #3
      Re: str() for containers

      In article <40d07ac6@rutge rs.edu>,
      "George Sakkis" <gsakkis@rutger s.edu> wrote:
      [color=blue]
      > I find the string representation behaviour of builtin containers
      > (tuples,lists,d icts) unintuitive in that they don't call recursively str()
      > on their contents (e.g. as in Java)[/color]

      Please find last week's answers to this question at


      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.

      Donn Cave, donn@u.washingt on.edu

      Comment

      • Dan Bishop

        #4
        Re: str() for containers

        Donn Cave <donn@u.washing ton.edu> wrote in message news:<donn-65345D.10415616 062004@nntp1.u. washington.edu> ...[color=blue]
        > In article <40d07ac6@rutge rs.edu>,
        > "George Sakkis" <gsakkis@rutger s.edu> wrote:
        >[color=green]
        > > I find the string representation behaviour of builtin containers
        > > (tuples,lists,d icts) unintuitive in that they don't call recursively str()
        > > on their contents (e.g. as in Java)[/color]
        >
        > Please find last week's answers to this question at
        > http://groups.google.com/groups?hl=e...e7a6469ac7b40b
        >
        > 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.[/color]

        All Java classes include a toString() method (defined in the root
        class java.lang.Objec t), 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.prin tln(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.prin tln(arr);
        }
        }

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

        Comment

        • Dan Bishop

          #5
          Re: str() for containers

          Donn Cave <donn@u.washing ton.edu> wrote in message news:<donn-65345D.10415616 062004@nntp1.u. washington.edu> ...[color=blue]
          > In article <40d07ac6@rutge rs.edu>,
          > "George Sakkis" <gsakkis@rutger s.edu> wrote:
          >[color=green]
          > > I find the string representation behaviour of builtin containers
          > > (tuples,lists,d icts) unintuitive in that they don't call recursively str()
          > > on their contents (e.g. as in Java)[/color]
          >
          > Please find last week's answers to this question at
          > http://groups.google.com/groups?hl=e...e7a6469ac7b40b
          >
          > 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.[/color]

          All Java classes include a toString() method (defined in the root
          class java.lang.Objec t), 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.prin tln(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.prin tln(arr);
          }
          }

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

          Comment

          • Donn Cave

            #6
            Re: str() for containers

            In article <ad052e5c.04061 72153.128f765f@ posting.google. com>,
            danb_83@yahoo.c om (Dan Bishop) wrote:
            [color=blue]
            > All Java classes include a toString() method (defined in the root
            > class java.lang.Objec t), 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.prin tln(lst);
            > }
            > }
            >
            > prints "[a, b, c]".[/color]

            OK, so it's ambiguous - you don't know from the result
            whether there are three elements, or two or one - if
            one of the elements has its own ", ".
            [color=blue]
            > (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.[/color]

            It would be fun to apply that reasoning to arithmetic
            operators. Which one does Java support?
            [color=blue]
            > 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.prin tln(arr);
            > }
            > }
            >
            > prints "[Ljava.lang.Stri ng;@df6ccd" (or something similar).[/color]

            Ah, I can see how appealing this system would be.
            What elegance!

            Donn Cave, donn@u.washingt on.edu

            Comment

            • Dan Bishop

              #7
              Re: str() for containers

              Donn Cave <donn@u.washing ton.edu> wrote in message news:<donn-19AA94.08563918 062004@nntp4.u. washington.edu> ...[color=blue]
              > In article <ad052e5c.04061 72153.128f765f@ posting.google. com>,
              > danb_83@yahoo.c om (Dan Bishop) wrote:
              >[color=green]
              > > All Java classes include a toString() method (defined in the root
              > > class java.lang.Objec t), which returns the string representation of
              > > that object...[big snip]
              > > 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.[/color]
              >
              > It would be fun to apply that reasoning to arithmetic
              > operators. Which one does Java support?[/color]

              toString() usually behaves more like Python's str than repr. An
              exception is Double.toString , which returns 16 signifcant digits.

              Jython uses toString() to implement both __str__ and __repr__ for Java
              classes.

              Comment

              • John Roth

                #8
                Re: str() for containers

                "George Sakkis" <gsakkis@rutger s.edu> wrote in message
                news:40d07ac6@r utgers.edu...[color=blue]
                > Hi all,
                >
                > I find the string representation behaviour of builtin containers
                > (tuples,lists,d icts) unintuitive in that they don't call recursively str()
                > on their contents (e.g. as in Java) :[/color]
                [color=blue]
                > It's even more cumbersome for containers of containers (e.g. lists of[/color]
                dicts,[color=blue]
                > etc.). Of course one can (or should) encapsulate such stuctures in a class
                > and define __str__ to behave as expected, but why not having it by default[/color]
                ?[color=blue]
                > Is there a good reason for this ?[/color]

                I don't think there's a ***good*** reason. The root of
                the issue is that the str() / repr() distinction is too simplistic
                for containers. The output of str() is supposed to be human
                readable, and the output of repr() is supposed to be able
                to round-trip through exec/eval (which is not always possible,
                but should be maintained if it is.)

                Human readable output from a container, however, needs
                to be very clear on the distinction between the container
                and the objects that are contained. It isn't always obvious
                whether using str() or repr() on the contained object is the
                best policy, and in some cases I suspect that something
                different from either would be helpful.

                The only clean solution I can see is to provide a third built-in
                that provides the "right" output when a container class needs
                to turn an object into a string. However, someone else
                is going to have to do the work of writing up the use
                cases and the PEP - I don't care enough.

                John Roth[color=blue]
                >
                > George
                >
                >[/color]


                Comment

                • Marcin 'Qrczak' Kowalczyk

                  #9
                  Re: str() for containers

                  On Sat, 19 Jun 2004 08:41:56 -0400, John Roth wrote:
                  [color=blue]
                  > The only clean solution I can see is to provide a third built-in
                  > that provides the "right" output when a container class needs
                  > to turn an object into a string.[/color]

                  What is the right thing e.g. for strings?

                  --
                  __("< Marcin Kowalczyk
                  \__/ qrczak@knm.org. pl
                  ^^ http://qrnik.knm.org.pl/~qrczak/

                  Comment

                  • Peter Hansen

                    #10
                    Re: str() for containers

                    Marcin 'Qrczak' Kowalczyk wrote:
                    [color=blue]
                    > On Sat, 19 Jun 2004 08:41:56 -0400, John Roth wrote:
                    >
                    >[color=green]
                    >>The only clean solution I can see is to provide a third built-in
                    >>that provides the "right" output when a container class needs
                    >>to turn an object into a string.[/color]
                    >
                    >
                    > What is the right thing e.g. for strings?[/color]

                    Exactly. ;-)

                    Comment

                    • Edward C. Jones

                      #11
                      Re: str() for containers

                      John Roth wrote:[color=blue]
                      > "George Sakkis" <gsakkis@rutger s.edu> wrote in message[color=green]
                      >>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) :[/color]
                      > The only clean solution I can see is to provide a third built-in
                      > that provides the "right" output when a container class needs
                      > to turn an object into a string. However, someone else
                      > is going to have to do the work of writing up the use
                      > cases and the PEP - I don't care enough.[/color]

                      For str of a container, I suggest using repr for strings in the
                      container and str for everything else.

                      Comment

                      • Donn Cave

                        #12
                        Re: str() for containers

                        Quoth "John Roth" <newsgroups@jhr othjr.com>:
                        ....
                        | I don't think there's a ***good*** reason. The root of
                        | the issue is that the str() / repr() distinction is too simplistic
                        | for containers. The output of str() is supposed to be human
                        | readable, and the output of repr() is supposed to be able
                        | to round-trip through exec/eval (which is not always possible,
                        | but should be maintained if it is.)

                        That's one way to look at it, but it's a perspective that will
                        always leave you dissatisfied with both str and repr.

                        Not only is repr-as-marshal not always possible, it's very widely
                        not implemented even when it could be, and anyone who relies on
                        this feature is asking for trouble. Human readable is as vacuous
                        an expectation as there could be for what str does, so it's hard
                        to say for sure you'll be disappointed there, but then it's just
                        impossible to imagine any solid basis for saying whether a value
                        is going to be human readable. I've seen what the documentation
                        says, and there has been plenty of discussion about this.

                        The way I see it, __str__ is about conversion to string data. It
                        really applies to only those objects that can naturally be converted
                        to a string. If lists had a __str__ function, then str(list) would
                        be the inverse of list(str), but since that would raise all kinds
                        of questions about what to do with lists containing other things
                        besides strings of length 1, there is no __str__ function. Instead,
                        str(list) calls __repr__.

                        Repr renders the object as a string. Not just the object's value
                        in a computational sense, so to speak, but the object implementation.
                        So it's typically more interesting to a programmer, than the program's
                        user. That could be seen as a human readability issue, but it puts
                        the point into better perspective - what's the user-oriented value
                        of a list as string? There isn't one.

                        Donn Cave, donn@drizzle.co m

                        Comment

                        Working...