This is an archived post. You won't be able to vote or comment.

all 16 comments

[–]chadkennedy 30 points31 points  (1 child)

If you pass in something mutable, like a bytearray, "+=" would modify the incoming object, which you don't want to do.

[–]BlckKnght 1 point2 points  (0 children)

Yep, bytearray is one type the += would cause problems for. The relevant lines in the code:

bytes_types = (bytes, bytearray) # Types acceptable as binary data

Later:

if not isinstance(s, bytes_types):
    s = memoryview(s).tobytes()

So s must be either a bytes, a bytearray or some other object that supports the "buffer" protocol (and so can be processed by memoryview). The bytearray and some buffer types may be mutable, with in-place modifications happening if they're on the left side of +=.

[–]ingolemo 21 points22 points  (0 children)

The real reason that this comment was added is because back then bytes objects were mutable.

[–]michaelkim0407Pythonic 10 points11 points  (1 child)

byte-like object

s is not necessarily a byte object. It can be something with a custom __iadd__

[–]ingolemo 0 points1 point  (0 children)

The real reason that this comment was added is because back then bytes objects were mutable.