Skip to content

Accept str and bytes subclasses in to_bytes - #109

Open
niklastheiler wants to merge 2 commits into
ParallelSSH:masterfrom
niklastheiler:fix-to-bytes-subclasses
Open

niklastheiler wants to merge 2 commits into
ParallelSSH:masterfrom
niklastheiler:fix-to-bytes-subclasses

Conversation

@niklastheiler

@niklastheiler niklastheiler commented Nov 25, 2026 •

Copy link
Copy Markdown

Resolves #106.

to_bytes() is declared cdef bytes, so Cython requires an exact bytes return value. Both branches could hand back a subclass unchanged: the input itself for a bytes subclass, or the result of encode() on a str subclass. Every API using to_bytes() then raised TypeError: Expected bytes, got <subclass>, for example Session.options_set, Session.userauth_password and import_pubkey_file.

This happens in practice with Ansible. AnsibleUnsafeText.encode() returns AnsibleUnsafeBytes, so NETCONF over ncclient's libssh transport fails (ansible-collections/ansible.netcommon#815).

Change

  • ssh/utils.pyx: both branches now go through bytes(). For an exact bytes object, bytes() returns the same object without a copy, so the common case does not change.
  • ssh/utils.c: regenerated with Cython 3.1.4, since CI builds from the committed C files.
  • tests/test_session.py: test_str_and_bytes_subclasses covers options_set, userauth_password and import_pubkey_file with a bytes subclass and with a str subclass whose encode() returns a bytes subclass. The test needs no SSH server.

Testing

Built locally on Python 3.12, Linux x86_64, with the embedded libssh:

  • Without the change, the new test fails with TypeError: Expected bytes, got _BytesSubclass.
  • With the change, it passes, along with test_should_not_segfault and test_set_timeout. This also holds for a build from the committed C files without Cython.

niklastheiler and others added 2 commits November 24, 2026 20:13
to_bytes() is declared to return bytes, which Cython enforces as an exact
type. Subclasses of bytes, or the result of encode() on a str subclass that
returns a bytes subclass, were returned as-is and raised
"TypeError: Expected bytes, got <subclass>" in every API using to_bytes,
e.g. Session.options_set, Session.userauth_password and import_*_file.

Wrap both branches in bytes(), which returns an exact bytes object as-is
without a copy, so the common case is unchanged.

Resolves ParallelSSH#106

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CI builds from the committed C files without Cython, so the to_bytes
fix was not part of the tested build.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
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.

to_bytes() fails with TypeError: Expected bytes, got <subclass> for subclasses of str/bytes

1 participant