Skip to content

Convert bytes to str sanely in argument conversion #5567

Closed

Description

@pekkaklarck

Currently if we have a keyword like

def example(arg: str):
    print(arg)

and use it with bytes like b"hello", automatic argument conversion converts the value to a string simply by calling str(value). This means that the keyword ends up getting a string "b'hello'". The conversion can be tested on the interpreter:

>>> str(b"hello")
"b'hello'"

This isn't very useful and can cause quite a lot of confusion. The keyword seems to work, or at least argument conversion doesn't fail, but the actual value is most likely not what expected.

A much better approach is mapping each bytes to a matching Unicode code point. This means that bytes like b"hello" is converted to a string "hello". This can be demonstrated as below:

>>> "".join(chr(o) for o in b"hello")
'hello'
>>> b"hello".decode("latin-1")  # simpler and faster than the above
'hello'

A major benefit of this approach is that it is symmetric to how strings are converted to bytes if you have a keyword that accepts arg: bytes and call it with a string like "hello". Simply calling bytes("hello") wouldn't even work and argument conversion uses "hello".encode("latin-1") that yields b"hello".

Another possible approach would be explicitly rejecting bytes when an argument has str as its type. I can see some benefits in that, but it would be inconsistent with how argument conversion works in general and especially how it works in str to bytes conversion already now.

Activity

  1. added this to the v7.4 milestone on Nov 30, 2025
  2. self-assigned this
    on Nov 30, 2025
  3. pekkaklarck commented on Nov 30, 2025

    @pekkaklarck
    MemberAuthor

    Notice that the key invariant is that bytes should be mapped directly to matching Unicode code points. We do this to the opposite direction already when an argument has type arg: bytes and the value is string. In practice what we want is this:

    >>> s = "Klärck"
    >>> b = bytes([ord(c) for c in s])
    >>> print(s)
    Klärck
    >>> print(b)
    b'Kl\xe4rck'
    >>> [ord(c) for c in s]
    [75, 108, 228, 114, 99, 107]
    >>> [o for o in b]
    [75, 108, 228, 114, 99, 107]

    This isn't really about text encodings. The fact that we can use Latin-1 encoding instead of converting each character separately is mostly an implementation detail:

    >>> b == s.encode("Latin-1")
    True
    >>> b.decode("Latin-1") == s
    True
  4. pekkaklarck commented on Nov 30, 2025

    @pekkaklarck
    MemberAuthor

    I noticed this issue when review PR #5554 that adds typing to the String library. The library has a keyword that currently looks like this:

    def encode_string_to_bytes(self, string, encoding, errors="strict"):
        """..."""
        return string.encode(encoding, errors)

    This is a reasonable implementation. If you call the keyword with a string, the result is something like this (using s from the previous comment):

    >>> s.encode("utf-8", "string")
    b'Kl\xc3\xa4rck'

    On the other hand. calling with bytes explicitly fails (but perhaps not in the nicest possible way):

    >>> b.encode("utf-8", "string")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'bytes' object has no attribute 'encode'

    In the PR the keyword is changed to this:

    def encode_string_to_bytes(self, string: str, encoding: str, errors: str = "strict") -> bytes:
        """..."""
        return string.encode(encoding, errors)

    This looks very good in itself, but due to how argument conversion currently handles conversion to str the behavior changes. After the PR is merged, if the keyword is called with bytes like b"hello", there's no exception anymore. Instead the value is converted to string "b'hello'" by argument conversion and the keyword then converts it to bytes b"b'hello'". This is not desirable.

    The keyword itself could handle this by using string: str | bytes as the typing instead of just string: str and then explicitly rejecting bytes with something like if isinstance(string, bytes): raise TypeError(...). It would work, but it would be rather strange if the typing advertised bytes support but the implementation would then reject. This also wouldn't fix the same issue with all other keywords that accept str and are used with bytes. I thus believe changing argument conversion makes much more sense.

  5. pekkaklarck commented on Nov 30, 2025

    @pekkaklarck
    MemberAuthor

    I marked this issue backwards incompatible, because handling bytes changes. This only happens if bytes aren't explicitly accepted, though, and the result are rather confusing, so I believe doing the change in a non-major release is fine. This should nevertheless be explicitly mentioned in the release notes.

  6. pekkaklarck commented on Nov 30, 2025

    @pekkaklarck
    MemberAuthor

    This is related to the enhanced bytes support tracked by #5548. Keywords that accept str now work better with bytes than earlier. Depending on the case, proper bytes support would require accepting str | bytes and returning corresponding value, though.

  7. added a commit that references this issue on Nov 30, 2025
    3555d5b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions