0
buf=b"foo"
buf+=b"bar"
print(type(buf))
print(buf)

this will print "bytes" and "foobar". I am confused, if bytes is supposed to be immutable, why does the mutation += works ?

Aaa Bbb
  • 627
  • 4
  • 12
  • 2
    It appends, meaning that you are not editing the byte, but adding to it. It rewrites the entire byte to do this also. https://stackoverflow.com/questions/12359190/for-python-3-2-why-does-adding-bytes-to-a-bytes-object-take-longer-as-more-byte – Larry the Llama Dec 10 '21 at 05:48
  • 3
    It is immutable. You didn't mutate anything, you created *a new bytes object* and re-assigned it to `buf`. Check the `id` before and after `buf+=b"bar"`, e.g. `print(id(buf))` – juanpa.arrivillaga Dec 10 '21 at 05:48
  • 1
    https://www.python.org/dev/peps/pep-3137/ – Mohit Patil Dec 10 '21 at 05:48
  • 1
    `x += y` is equivalent to `x = x.__iadd__(y)` if that exists on the type; otherwise it falls back to `x = x + y` (which calls `__add__` and/or `__radd__` depending on subclassing and `NotImplemented`). – o11c Dec 10 '21 at 06:22
  • 1
    The correct test is: `a = 'a'; b = a; a += 'c'; print(b)` — The value did not mutate, `a` has a completely different value now. – deceze Dec 10 '21 at 08:19

1 Answers1

1

You are confused because you assume that the += operator mutates the state. That's not always the case. In fact here the operator creates a new object for you under the hood, which you can verify by comparing id.

Chris
  • 26,361
  • 5
  • 21
  • 42
freakish
  • 54,167
  • 9
  • 132
  • 169