473,657 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

############### ############### #############
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 1534
George Sakkis wrote:
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) :


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******@rutge rs.edu>,
"George Sakkis" <gs*****@rutger s.edu> wrote:
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)


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.washingt on.edu
Jul 18 '05 #3
Donn Cave <do**@u.washing ton.edu> wrote in message news:<do******* *************** **@nntp1.u.wash ington.edu>...
In article <40******@rutge rs.edu>,
"George Sakkis" <gs*****@rutger s.edu> wrote:
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)


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.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).
Jul 18 '05 #4
Donn Cave <do**@u.washing ton.edu> wrote in message news:<do******* *************** **@nntp1.u.wash ington.edu>...
In article <40******@rutge rs.edu>,
"George Sakkis" <gs*****@rutger s.edu> wrote:
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)


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.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).
Jul 18 '05 #5
In article <ad************ **************@ posting.google. com>,
da*****@yahoo.c om (Dan Bishop) wrote:
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]".
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.prin tln(arr);
}
}

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


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

Donn Cave, do**@u.washingt on.edu
Jul 18 '05 #6
Donn Cave <do**@u.washing ton.edu> wrote in message news:<do******* *************** **@nntp4.u.wash ington.edu>...
In article <ad************ **************@ posting.google. com>,
da*****@yahoo.c om (Dan Bishop) wrote:
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.


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*****@rutger s.edu> wrote in message
news:40******@r utgers.edu...
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) : 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

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

Similar topics

11
25729
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
2717
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 reference to 'C' object >>>
14
8205
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 present the shared memory contains a few fixed-size structs, but I really need to be able to store more complex variable-sized data in there. So the next task is to work out how to store C++ objects, and if possible STL containers, in this shared...
18
3043
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 frequently, I thought it'd be a better idea to manage additional containers which are initialized with pointers to the objects in the primary containers and sort those (only pointers have to be copied around then). However, that also means if I...
8
3943
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 example: class A { public: const vector<int>& getTable() { return m_table; }
2
1592
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, say. When an item is to be inserted/removed into/from these custom containers, customNew and customDelete is called.
1
2266
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 doing // IO, so we could assume to have, for 2 containers as exemple: Ext1ct1, Ext1ct2, Ext2ct1, Ext2ct2
15
4075
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 containers destructors virtual >
11
1918
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 allows the handling of much bigger amounts of data. However, there are cases where this turns out to be inefficient for at least two reasons: A) Allocations and deallocations on heap are much slower. B) Memory access on stack is more cache...
0
8425
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8326
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8743
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2745
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.