QUERY · ISSUE
bytes.find() differs from CPython
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).
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?