Skip to content

Fix i2c_msg.__bytes__ return type in the type stub - #148

Open
abdurrahman-nexthop wants to merge 1 commit into
kplindegaard:masterfrom
abdurrahman-nexthop:fix-i2c-msg-bytes-stub
Open

abdurrahman-nexthop wants to merge 1 commit into
kplindegaard:masterfrom
abdurrahman-nexthop:fix-i2c-msg-bytes-stub

Conversation

@abdurrahman-nexthop

Copy link
Copy Markdown

i2c_msg.__bytes__ is declared in smbus2.pyi as returning str, but the implementation returns ctypes.string_at(self.buf, self.len), which is bytes:

https://github.com/kplindegaard/smbus2/blob/master/smbus2/smbus2.py#L181-L182

The class's own __str__ depends on that — it calls self.__bytes__().decode(errors="ignore"), which is only valid on bytes.

Since the package is py.typed, the wrong annotation propagates to callers: bytes(msg) is inferred as str, so passing the result anywhere that expects bytes is reported as an error.

from smbus2 import i2c_msg

msg = i2c_msg.write(0x50, [1, 2, 3])
reveal_type(bytes(msg))   # declared: str   actual: bytes

Same class of issue as #142 / #143, which corrected __iter__ on the neighbouring line.

🤖 Generated with Claude Code

i2c_msg.__bytes__ is declared as returning str, but it returns

    ctypes.string_at(self.buf, self.len)

which is bytes. The class's own __str__ relies on that -- it calls
self.__bytes__().decode(errors="ignore"), which is only valid on bytes.

Because the package is py.typed, this propagates to callers: bytes(msg)
is inferred as str, so passing the result anywhere expecting bytes is
reported as an error by a type checker.

Same class of issue as kplindegaard#142 / kplindegaard#143, which corrected __iter__ on the
neighbouring line.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@kplindegaard

Copy link
Copy Markdown
Owner

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants