str(bytes) in Python 3.0

Terry Reedy tjreedy at udel.edu
Sun Apr 13 02:10:19 EDT 2008


"John Roth" <johnroth1 at gmail.com> wrote in message 
news:29f280cc-4b33-4863-beee-d231df3d9a61 at u3g2000hsc.googlegroups.com...
| On Apr 12, 8:52 am, j... at pobox.com (John J. Lee) wrote:
| > Christian Heimes <li... at cheimes.de> writes:
| > > Gabriel Genellina schrieb:
| > >> On the last line, str(x), I would expect 'abc' - same as str(x, 
'ascii')
| > >> above. But I get the same as repr(x) - is this on purpose?
| >
| > > Yes, it's on purpose but it's a bug in your application to call str() 
on
| > > a bytes object or to compare bytes and unicode directly. Several 
months
| > > ago I added a bytes warning option to Python. Start Python as 
"python
| > > -bb" and try it again. ;)
| >
| > Why hasn't the one-argument str(bytes_obj) been designed to raise an
| > exception in Python 3?
| >
| > John
|
| Because it's a fundamental rule that you should be able to call str()
| on any object and get a sensible result.
|
| The reason that calling str() on a bytes object returns a bytes
| literal rather than an unadorned character string is that there are no
| default encodings or decodings: there is no way of determining what
| the corresponding string should be.

In having a double meaning, str is much like type.  Type(obj) echoes the 
existing class of the object.  Type(o,p,q) attempts to construct a new 
class.  Similarly, Str(obj) gives a string representing the obj (which, for 
a string, is the string;-).  Str(obj,obj2) attemps to construct a new 
string.

tjr






More information about the Python-list mailing list