Skip to content

Function argument error handling improvements #1055

@davidhewitt

Description

@davidhewitt

This is a sketch of ideas for a follow-up of #1050 to enable #[pyfunction] (and #[pymethods] etc.) to report better errors for function inputs.

Imagine that the following #[pyfunction]:

#[pyfunction]
fn foo(tup: (i32, &str)) {
    println!("{:?}", tup)
}

After #1050, the error message when calling this function with invalid arguments is already much improved from PyO3 0.11.1:

>>> foo(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert None to PyTuple

I think that this error message can yet be improved further. There's two ways in which I'd like to see this improve:

  1. Mention the argument which failed to convert.
    Naming the function argument which failed to convert will help users locate exactly which function input is incorrect.

  2. Provide mypy-style type annotations for the target type, where possible.
    It's great to see that None can't convert to PyTuple, but as a Python user really what I need to see is that the expected type is Tuple[int, str].

Put together, this might mean that our foo function above would output error messages like the below:

>>> foo(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert None to `Tuple[int, str]` (when trying to extract argument `tup`)

I'm not super attached to the exact wording of the above if someone else has a better idea / something easier to implement.

Later today I'm going to add some thoughts on how these two pieces could be implented if anyone in the community is interested in championing these improvements.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions