Skip to content

Define parse in terms of tryparse #43149

@jakobnissen

Description

@jakobnissen

Historically, parse was created before tryparse in Julia. However, tryparse is more fundamental and generally useful, since it allows the caller to handle badly formatted strings. The caller can then decide whether to error or handle the input in another way. By erroring when nothing is returned, tryparse can easily be turned into parse - but it is not easy the other way around.

I propose that we:

  • Define parse in terms of tryparse by adding the following fallback definition:
function parse(::Type{T}, s::AbstractString) where T
    y = tryparse(T, s)
    y === nothing && throw(ArgumentError("Cannot parse as $T: \"$s\""))
    return y
end
  • Recommend users to implement tryparse(::Type{T}, s::AbstractString) and only implement parse if they need a custom error message.

This way, the user gets both parse and tryparse, only having to implement one function, and as an added bonus, we emphasize that users should implement the more efficient tryparse as the primary mechanism.

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsThis change adds or pertains to documentation

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions