Page 1 of 1

bytes() makes a new copy of a bytes variable

Posted: Thu Aug 06, 2020 7:16 pm
by kjw
I noticed this in CircuitPython but just tested a micro:bit and it does the same thing. bytes() makes a new copy of an object even if it's bytes() already.

Code: Select all

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>> 
>>> a = b"Original"
>>> b = a
>>> c = bytes(a)
>>> type(a)
<class 'bytes'>
>>> a is b
True
>>> a is c
False
>>> id(a)
536871968
>>> id(b)
536871968
>>> id(c)
536871840
I tried a few versions of CPython and it just returns the original. Is there a reason for a copy being made here of this (immutable) type?

Re: bytes() makes a new copy of a bytes variable

Posted: Fri Aug 07, 2020 7:34 am
by pythoncoder
This does seem like a bug. The Unix build has the same behaviour.

Strings behave correctly. On the Unix build:

Code: Select all

>>> s = 'rats'
>>> t = str(s)
>>> t is s
True
>>> 
which is as per CPython.

Re: bytes() makes a new copy of a bytes variable

Posted: Fri Sep 18, 2020 11:40 am
by Iyassou
I've submitted a pull request for this :)