Skip to content

Improve invalid input type handling in tomllib.loads #124835

Closed
@hukkin

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

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