← index #3158Issue #6320
Off-topic · high · value 0.845
QUERY · ISSUE

py: bytes() won't call obj.__bytes__()

openby ThunderEXopened 2017-06-21updated 2024-08-28
docs

I defined a class with bytes method. Calling bytes() on its instance should redirect to its bytes method, but it doesn't.

Can this be fixed?

CANDIDATE · ISSUE

bytes() creates a new object for an existing bytes object

closedby kevinjwaltersopened 2020-08-07updated 2020-09-24
py-core

MicroPython will create a new object for bytes(var) when var is of type bytes. This behaviour is different to three versions of CPython that I tried and given that it's an immutable type seems unnecessary and inefficient. Example on micro:bit:

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

Discussed on MicroPython Forum: bytes() makes a new copy of a bytes variable.

I noticed this originally on CircuitPython 5.3.0.

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied