473,386 Members | 1,873 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

str() for containers

Hi all,

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) :

###########################################
class A(object):
def __str__(self): return "a"
print A() a print [A()] [<__main__.A object at 0xa1a5c6c>] print map(str,[A()])

['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
Jul 18 '05 #1
11 1508
George Sakkis 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) :


They use repr(), not str():
class Foo(object): .... def __repr__(self):
.... return 'foo'
.... print Foo() foo print [Foo()]

[foo]
Jul 18 '05 #2
In article <40******@rutgers.edu>,
"George Sakkis" <gs*****@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=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.

Donn Cave, do**@u.washington.edu
Jul 18 '05 #3
Donn Cave <do**@u.washington.edu> wrote in message news:<do************************@nntp1.u.washingto n.edu>...
In article <40******@rutgers.edu>,
"George Sakkis" <gs*****@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=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.


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).
Jul 18 '05 #4
Donn Cave <do**@u.washington.edu> wrote in message news:<do************************@nntp1.u.washingto n.edu>...
In article <40******@rutgers.edu>,
"George Sakkis" <gs*****@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=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.


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).
Jul 18 '05 #5
In article <ad**************************@posting.google.com >,
da*****@yahoo.com (Dan Bishop) wrote:
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]".
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 ", ".
(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.
It would be fun to apply that reasoning to arithmetic
operators. Which one does Java support?
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).


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

Donn Cave, do**@u.washington.edu
Jul 18 '05 #6
Donn Cave <do**@u.washington.edu> wrote in message news:<do************************@nntp4.u.washingto n.edu>...
In article <ad**************************@posting.google.com >,
da*****@yahoo.com (Dan Bishop) wrote:
All Java classes include a toString() method (defined in the root
class java.lang.Object), 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.


It would be fun to apply that reasoning to arithmetic
operators. Which one does Java support?


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.
Jul 18 '05 #7
"George Sakkis" <gs*****@rutgers.edu> wrote in message
news:40******@rutgers.edu...
Hi all,

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) : 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 ?
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
George

Jul 18 '05 #8
On Sat, 19 Jun 2004 08:41:56 -0400, John Roth wrote:
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.


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

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

Jul 18 '05 #9
Marcin 'Qrczak' Kowalczyk wrote:
On Sat, 19 Jun 2004 08:41:56 -0400, John Roth wrote:

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.

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


Exactly. ;-)
Jul 18 '05 #10
John Roth wrote:
"George Sakkis" <gs*****@rutgers.edu> wrote in message
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) :

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.


For str of a container, I suggest using repr for strings in the
container and str for everything else.
Jul 18 '05 #11
Quoth "John Roth" <ne********@jhrothjr.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, do**@drizzle.com
Jul 18 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: cjl | last post by:
Hey all: I want to convert strings (ex. '3', '32') to strings with left padded zeroes (ex. '003', '032'), so I tried this: string1 = '32' string2 = "%03s" % (string1) print string2 >32
12
by: Ron Garret | last post by:
Why doesn't this work? >>> from weakref import ref >>> class C(str): pass .... >>> ref(C()) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: cannot create weak...
14
by: phil_gg04 | last post by:
Dear C++ Experts, Over the last couple of months I have been writing my first program using shared memory. It has been something of an "in-at-the-deep-end" experience, to say the least. At...
18
by: Matthias Kaeppler | last post by:
Hi, in my program, I have to sort containers of objects which can be 2000 items big in some cases. Since STL containers are based around copying and since I need to sort these containers quite...
8
by: Gregory | last post by:
I have a question about using STL containers in C++ class public interface. Lets say that I want to return some container from class method or accept class method parameter as some container. For...
2
by: bob | last post by:
Hi, Given: 1) Custom containers that have nothing to do with vector, deque, list, map etc, 2) a custom version of new and delete defined for these containers, customNew and customDelete,...
1
by: Jean-Marc Blaise | last post by:
IBM recommends to place each ts container on a different physical disk. What about the impacts if all containers (DMS) are in the same FS (supported by multiple disks) ? Does DB2 preallocate...
15
by: Nindi73 | last post by:
HI If I define the class DoubleMap such that struct DoubleMap : public std::map<std::string, double>{}; Is there any overhead in calling std::map member functions ? Moreover are STL...
11
by: jimxoch | last post by:
Hi list, Most STL containers are storing their data on the heap. (although some std::string implementations are notable exceptions) Of course, using the heap as storage increases flexibility and...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.