← index #5123PR #11631
Likely Duplicate · high · value 0.432
QUERY · ISSUE

bytes.find() differs from CPython

openby doc-hexopened 2019-09-19updated 2019-09-26
py-core

In Cpython (at least) I can find by integer using bytes.find(). Micropython doesn't allow this and only acceptsbytes as an argument to find.

Micropython:

>>> s = b'ABC'
>>> s.find(b'B')
1
>>> s.find(66)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert 'int' object to str implicitly
>>> 

Desktop python:

>>> s = b'ABC'
>>> s.find(b'B')
1
>>> s.find(66)
1

Here is the check that's failing, but additional code would be needed to convert int (0..255) into byte.

https://github.com/micropython/micropython/blob/master/py/objstr.c#L693

This bug bit me deep in some QR encoding logic.

CANDIDATE · PULL REQUEST

py/objstr.c: Add support for bytes.find(int).

openby jimmoopened 2023-05-26updated 2023-06-27
py-core

As requested in #11617

Pros:

  • Existing Python code "just works". (i.e. CPython compatibility is always good)
  • The Python alternative is a bit awkward, i.e. given a byte value, to use find/index you have to make it into a single-element bytes (e.g b.find(chr(n).encode()).

Cons:

  • Adds ~+72~ +56 bytes on PYBV10.

Also added some tests, and some more tests for bytes/bytearray index/find ops. @andrewleech can you please look at bytearray_byte_operations.py and confirm whether it was intentional that the .index tests didn't use the b'' prefix?

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