Skip to content

Improve invalid input type handling in tomllib.loads #124835

Closed

Description

@hukkin

Feature or enhancement

Proposal:

tomllib.loads only accepts str as input. Given bytes, it throws

TypeError: a bytes-like object is required, not 'str'

This is a bubbled up exception from the replace method on line

src = s.replace("\r\n", "\n")
which is otherwise fine, but the message has bytes and str the wrong way around, which can be very confusing. I propose catching the exception and raising a new TypeError with an improved message.

While at it, I also propose catching any AttributeErrors from this line of code and raising the same new TypeError instead. As a result, a sensible TypeError is raised in nearly all cases where incorrect type is passed in.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

Original issue report by @mechsin on Tomli's issue tracker: hukkin/tomli#223
PR: #124587

Linked PRs

Activity

  1. added a commit that references this issue on Oct 2, 2024
  2. StanFromIreland commented on Apr 17, 2025

    @StanFromIreland
    Member

    Do we want to backport this change? It is partly a bug fix (error message is flipped). Maybe it could be split?

    See also: #132655

  3. hauntsaninja commented on Apr 17, 2025

    @hauntsaninja
    Contributor

    I didn't backport because it can change the exception type (also because slightly less confusing error messages that aren't super critical are little more feature than bug, changes to error messages do sometimes break folks)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions