New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Improve doc for str(bytesobject) #57747
Comments
The docstring associated with str() says: str(string[, encoding[, errors]]) -> str Create a new string object from the given encoded string. When it is stated in the on-line documentation:: When only object is given, this returns its nicely printable representation. My issue comes when I tried to convert bytes to str. As stated in the documentation, and to avoid implicit behavior, converting str to bytes cannot be done without giving an encoding (using bytes(my_str, encoding=..) or my_str.encode(...). bytes(my_str) will raise a TypeError). But if you try to convert bytes to str using str(my_bytes), python will returns you the so-called nicely printable representation of the bytes object). ie. :: >>> bytes("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> str(b"foo")
"b'foo'" As a matter of coherency and to avoid silent errors, I suggest that str() of a byte object without encoding raise an exception. I think it is usually what people want. If one wants a *nicely printable representation* of their bytes object, they can call explicitly the repr() function and will quickly see that what they just printed is wrong. But if they want to convert a byte object to its unicode representation, they will prefer an exception rather than a silently failing converting which leads to an unicode string starting with 'b"' and ending with '"'. |
I agree with you that this is inconsistent. However, having str raise an error is pretty much a non-starter as a suggestion. str always falls back to the repr; in general str(obj) should always return some value, otherwise the assumptions of a *lot* of Python code would be broken. Personally I'm not at all sure why str takes encoding and errors arguments (I never use them). I'd rather there be only one way to do that, decode. In other words, why do we have special case support for byte strings in the str conversion function? But I don't think that can be changed either, so I think we are stuck with documenting the existing situation better. Do you want to propose a doc patch? |
Probably because the unicode type also did in 2.x. >>> str(memoryview(b"foo"), "ascii")
'foo' |
Perhaps it may raises a warning ? ie, the only reason encoding exists if for the conversion of bytes (or something which looks like bytes) to str. Do you think it may be possible to special case the use of str for bytes (and bytesarray) with something like this: def str(object, encoding=None, errors=None):
if encoding is not None:
# usual work
else:
if isinstance(object, (bytes, bytesarray)):
warning('Converting bytes/bytesarray to str without encoding, it may not be what you expect')
return object.__str__() But by the way, adding warnings and special case everywhere seems not too pythonic.
The docstring for str() should looks like something like, in my frenglish way of writing english :: Create a new string object from the given encoded string. If object is bytes, bytesarray or a buffer-like object, encoding and error WARNING, if encoding is not set, the object is converted to a nicely Perhaps a warning may be added in the on-line documentation, such as :: .. warning:: Whould you like a .diff on top of the current mercurial repository ? |
A diff would be great. We try to use warnings sparingly, and I don't think this is a case that warrants it. Possibly a .. note is worthwhile, perhaps with an example for the bytes case, but even that may be too much. I also wouldn't use the wording "is totally different from what you would expect", since by now I do expect it :). How about something like "the result will not be the decoded version of the bytes, but instead will be the repr of the object", with a cross link to repr. |
Well, I forgot to mention it in my previous message, but there is already a warning that you can activate with the -b option: $ ./python -b
Python 3.3.0a0 (default:6b6c79eba944, Dec 6 2011, 11:11:32)
[GCC 4.5.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str(b"")
__main__:1: BytesWarning: str() on a bytes instance
"b''" And you can even turn it into an error with -bb: $ ./python -bb
Python 3.3.0a0 (default:6b6c79eba944, Dec 6 2011, 11:11:32)
[GCC 4.5.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str(b"")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
BytesWarning: str() on a bytes instance However, -b is highly unlikely to become the default, for the reasons already explained. It was mainly meant to ease porting from Python 2. |
A note in the docs (without note/warning directives, just a note) and maybe the docstring would be good. It should better explain that str has two uses: converting anything to a str (using __str__ or __repr__), decode buffer to str (with encoding and errors arguments). str(b'') is a case of the first use, not the second (and likewise %s formatting). |
I think Eric's suggestion is the proper approach. |
This may have been addressed to some extent by bpo-14783: |
Attaching a proposed patch along the lines suggested by Éric. |
Instead of documenting what *encoding* and *errors* do, I would just say that str(bytesobj, encoding, errors) is equivalent to bytesobj.decode(encoding, errors) (assuming it really is). I don't like encodings/decodings done via the str/bytes constructors, and I think the docs should encourage the use of bytes.decode/str.encode. |
Good suggestion. And yes, code is shared in the following way: http://hg.python.org/cpython/file/d3c7ebdc71bb/Objects/bytesobject.c#l2306 One thing that would need to be addressed in the str() version is if bytesobj is a PEP-3118 character buffer, after which it falls back to bytesobj.decode(encoding, errors). I will update the patch so people can see how it looks. |
Indeed: >>> m = memoryview(b"")
>>> str(m, "utf-8")
''
>>> m.decode("utf-8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'memoryview' object has no attribute 'decode' |
Note: "character buffer" isn't a term we use anymore (in Python 3, that is). |
Attaching updated patch based on Ezio and Antoine's comments. Let me know if I'm not using the correct or preferred terminology around buffer objects and the buffer protocol. It doesn't seem like the section on the buffer protocol actually says what objects implementing the buffer protocol should be called. I gather indirectly from the docs that such objects are called "buffer objects" (as opposed to just "buffers"): |
Reattaching patch (a line was missing). |
+ str(bytes, encoding[, errors='strict']) Why not simply str(bytes, encoding='utf-8', errors='strict')? (Your signature suggests that str(b'abc', 'strict') should work.) + the string itself. This behavior differs from :func:`repr` in that the I'm not sure this is the right place where to explain the differences between __str__ and __repr__ (or maybe it is?). Also doesn't str() falls back on __repr__ if __str__ is missing? Does :meth:`__str__` link to object.__str__? + If *encoding* or *errors* is given, and/or + (or :class:`bytearray`) object, then :func:`str` calls I would use 'is equivalent to', rather than 'calls'. + :meth:`bytes.decode(encoding, errors) <bytes.decode>` on the object :meth:`bytes.decode` should be enough. + Passing a :func:`bytes <bytes>` :func:`bytes` should be enough (if it isn't, maybe you want :func:`.bytes`). |
New patch incorporating Ezio's suggestions, along with some other changes. |
Updating patch after Ezio's review on Rietveld. |
Attaching new patch to address Ezio's further comments (for the convenience of comparing in Rietveld). I will be committing this. |
I left a few remarks. The patch is very nice, thanks! |
Thanks, Éric! (And thanks also to Ezio who helped quite a bit with the improvements.) I replied to your comments on Rietveld. |
New changeset f32f1cb508ad by Chris Jerdonek in branch '3.2': New changeset 6630a1c42204 by Chris Jerdonek in branch '3.3': New changeset 325f80d792b9 by Chris Jerdonek in branch '3.3': New changeset 59acd5cac8b5 by Chris Jerdonek in branch 'default': |
New changeset 5c39e3906ce9 by Chris Jerdonek in branch '3.2': |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: